<template>
  <div class="home1">
    <div class="header">
      <div class="logo"></div>
      <div class="titleMain">
        <h1>酸轧生产效率监控</h1>
      </div>
    </div>
    <div class="page-layout">
      <div class="area top-svg">
        <!-- SVG 图 -->
        <div ref="svgContainer" style="height: 100%; width: 100%; z-index: 2; position: relative;">
          <svg-load :name="technologicalName" style="height: 100%; width: 100%"></svg-load>
        </div>

        <!-- 速度仪表盘 -->
        <div id="middle_speed1" class="speed-gauge"></div>
        <div id="middle_speed2" class="speed-gauge"></div>
        <div id="middle_speed4" class="speed-gauge"></div>
        <div id="middle_speed5" class="speed-gauge"></div>
        <!-- 轧机入口速度：改为白色字体显示，无背景 -->
        <div class="speed-text" id="middle_speed6">
          <p>{{ Math.round(mill_enter_speed) }}</p>
          <p style="font-size: 0.5vw; margin-top: 0.2vh;">m/min</p>
        </div>

        <!-- 延伸率 -->
        <div class="elongation_set semitransp_box">
          <p>SET </p>
          <p>{{ numberFormat3(elongationSet) }} %</p>
        </div>
        <div class="elongation_act semitransp_box">
          <p>ACT </p>
          <p :style="elongationAlarm ? 'color:red' : ''">{{ numberFormat(elongationAct, 2) }} %</p>
        </div>

        <!-- 拉矫机模式 -->
        <div class="sub_open semitransp_box" :style="sub_open ? 'background:red' : ''">
          <p>OPEN</p>
        </div>
        <div class="sub_relax semitransp_box" :style="sub_relax ? 'background:red' : ''">
          <p>RELAX</p>
        </div>
        <div class="sub_closed semitransp_box" :style="sub_closed ? 'background:red' : ''">
          <p>CLOSED</p>
        </div>

        <!-- 活套信息 -->
        <!-- <div class="inlet_looper semitransp_box">
          <p>入口活套：</p>
          <p><span :class="inletLooper * 1 < 3000 ? 'text-red' : ''">{{ numberFormat(inletLooper / 100) }}</span> %</p>
        </div>
        <div class="inlet_looper_time semitransp_box">
          <p>{{ inletLooperTime }}</p>
        </div>
        <div class="export_looper semitransp_box">
          <p>出口活套：</p>
          <p><span :class="exportLooper * 1 < 3000 ? 'text-red' : ''">{{ numberFormat(exportLooper / 100) }}</span> %</p>
        </div>
        <div class="export_looper_time semitransp_box">
          <p>{{ exportLooperTime }}</p>
        </div> -->

        <!-- 速度信息 -->
        <!-- <div class="ypj_speed semitransp_box">
          <p>圆盘剪速度</p>
        </div>
        <div class="tcm_speed semitransp_box">
          <p>工艺段速度</p>
        </div> -->

        <!-- 开卷机剩余长度 -->
        <div class="uncoiler_remaining_length_a semitransp_box">
          <!-- <p>#1开卷机剩余长度：</p> -->
          <p>{{ numberFormat(uncoiler_remaining_length_a) }} m</p>
        </div>
        <div class="uncoiler_remaining_length_b semitransp_box">
          <!-- <p>#2开卷机剩余长度：</p> -->
          <p>{{ numberFormat(uncoiler_remaining_length_b) }} m</p>
        </div>

        <!-- 卷取长度 -->
        <!-- <div class="coiler_remaining_length_a semitransp_box">
          <p>卷取长度：</p>
          <p>{{ numberFormat(coiler_remaining_length_a) }} m</p>
        </div> -->

        <!-- 厚度偏差 -->
        <div class="targetthickness semitransp_box">
          <p>T/L：</p>
          <p>{{ numberFormat3(homeBatchData - Targetthickness) }} mm/{{ numberFormat(coiler_remaining_length_a) }} m</p>
        </div>

        <!-- 轧机入口速度（已改为仪表盘显示，原文本框注释） -->
        <!-- <div class="mill_enter_speed semitransp_box">
          <p>轧机入口速度：</p>
          <p>{{ numberFormat(mill_enter_speed) }} mpm</p>
        </div> -->

        <!-- 工艺段套量 -->
        <!-- <div class="tech_loop semitransp_box">
          <p>工艺段套量：</p>
          <p><span :class="techLooperData * 1 < 4000 ? 'text-red' : ''">{{ numberFormat(techLooperData / 100) }}</span> %</p>
        </div> -->

        <!-- 新增：5个小蓝条（位置和数据待调整） -->
        <div class="blue_bar_1 semitransp_box">
          <p>AI：</p>
          <p :style="svgInfo.extAISetFlag === 1 ? 'color: #00ff00;' : 'color: #ff0000;'">{{ svgInfo.extAISet || 0 }}
            m/min</p>
        </div>
        <div class="blue_bar_2 semitransp_box">
          <p>AI：</p>
          <p :style="svgInfo.craftAISetFlag === 1 ? 'color: #00ff00;' : 'color: #ff0000;'">{{ svgInfo.craftAISet || 0 }}
            m/min</p>
        </div>
        <div class="blue_bar_3 semitransp_box">
          <p>AI：</p>
          <p :style="svgInfo.entAISetFlag === 1 ? 'color: #00ff00;' : 'color: #ff0000;'">{{ svgInfo.entAISet || 0 }}
            m/min</p>
        </div>
        <div class="blue_bar_4 semitransp_box">
          <!-- <p>1#横切剪实际切头米数：</p> -->
          <p>{{ svgInfo.crossCuttingShears1Actual || 0 }} m</p>
        </div>
        <div class="blue_bar_5 semitransp_box">
          <!-- <p>2#横切剪实际切头米数：</p> -->
          <p>{{ svgInfo.crossCuttingShears2Actual || 0 }} m</p>
        </div>

        <!-- 1#矫直机压下量 -->
        <div class="blue_bar_6 semitransp_box">
          <p>SET：</p>
          <p>{{ svgInfo.straightener1EntSet || 0 }}</p>
        </div>
        <div class="blue_bar_7 semitransp_box">
          <p>ACT：</p>
          <p>{{ svgInfo.straightener1EntFbk || 0 }}</p>
        </div>
        <div class="blue_bar_8 semitransp_box">
          <p>SET：</p>
          <p>{{ svgInfo.straightener1ExtSet || 0 }}</p>
        </div>
        <div class="blue_bar_9 semitransp_box">
          <p>ACT：</p>
          <p>{{ svgInfo.straightener1ExtFbk || 0 }}</p>
        </div>

        <!-- 2#矫直机压下量 -->
        <div class="blue_bar_10 semitransp_box">
          <p>SET：</p>
          <p>{{ svgInfo.straightener2EntSet || 0 }}</p>
        </div>
        <div class="blue_bar_11 semitransp_box">
          <p>ACT：</p>
          <p>{{ svgInfo.straightener2EntFbk || 0 }}</p>
        </div>
        <div class="blue_bar_12 semitransp_box">
          <p>SET：</p>
          <p>{{ svgInfo.straightener2ExtSet || 0 }}</p>
        </div>
        <div class="blue_bar_13 semitransp_box">
          <p>ACT：</p>
          <p>{{ svgInfo.straightener2ExtFbk || 0 }}</p>
        </div>

        <!-- 拉矫机模式 -->
        <div class="blue_bar_14 semitransp_box">
          <!-- <p>MOD：</p> -->
          <p>
            <span :style="levelerModeText !== '未启用' ? 'color: #00ff00;' : 'color: #ff0000;'">
              {{ levelerModeText }}
            </span>
          </p>
        </div>

        <!-- 烘干箱温度 -->
        <div class="blue_bar_16 semitransp_box">
          <!-- <p>烘干箱温度实际值：</p> -->
          <p>{{ svgInfo.dryerTemp || 0 }} ℃</p>
        </div>

        <!-- 酸位柱状图（使用ECharts渲染，显示在SVG上方） -->
        <div id="acidBarsChart" class="acid-bars-svg"></div>


        <!-- 剩余时长进度条 -->
        <div class="time_div all_time" :style="'width:' + timeAllWidth + 'vw'" style="left:0vw">
          <span>{{ '剩余时长(S) ' + rollCoilLeftTime + ' / ' + rollCoilAllTime + ' 计划时长(S)' }}</span>
          <div
            :style="'width:' + (Math.min(Math.abs(rollCoilLeftTime / rollCoilAllTime * (timeAllWidth / 2)), timeAllWidth / 2)) + 'vw;'"
            class="time_div" :class="rollCoilLeftTime < 0 ? 'out_time' : 'normal_time'"></div>
        </div>

        <!-- 开卷机剩余长度显示 -->
        <div class="tr-length" style="right: 1vw; bottom: 14vh">
          <!-- <span>{{ svgInfo.trLength1 }}m</span> -->
        </div>
        <div class="tr-length" style="right: 1.5vw; bottom: 8vh">
          <!-- <span>{{ svgInfo.trLength2 }}m</span> -->
        </div>
      </div>
      <div class="container">
        <div class="coils">
          <div v-for="index in 13" :key="index"><img src="/src/assets/images/acidRolling/coil-green.png" /></div>
        </div>
        <div class="main-container">
          <div class="area coils-info">
            <div class="coils-info-item">
              <div v-for="item in coilInfo" :key="item.extId" class="coils-info-item-content"
                :style="{ color: item.color }">
                <span class="text-coil" :style="{ color: coilColorMap?.colors?.[item.entid] }">{{ item.entid }}</span>
                <span class="text-coil" :style="{ color: coilColorMap?.colors?.[item.entid] }">{{ item.steelGrade
                }}</span>
                <span class="text-data">{{ item.ys }}</span>
                <span class="text-data">{{ item.hotThkAim }}</span>
                <span class="text-data">{{ item.hotFlatMin }}</span>
                <span class="text-data">{{ item.outMatMaxThick }}</span>
                <span class="text-data">{{ item.outMatWidth }}</span>
              </div>
            </div>
            <!-- 颜色条区域，相对于整个容器 -->
            <div class="bars" style="display: flex; flex-wrap: nowrap; width: 100%; height: 2vh">
              <div v-for="item in coilInfo" :key="`bar-${item.entid}`" class="coils-info-bars" :style="{
                backgroundColor: coilColorMap?.colors?.[item.entid],
                width: `${getWidth(item.entid) || 0}%`,
              }"></div>
            </div>
          </div>
          <div class="areas">
            <div class="area">
              <div class="title">
                <img src="/src/assets/images/acidRolling/title-icon.png" />
                <span>雷达图标题</span>
              </div>
              <div style="height: 22vh">
                <graph-radar />
              </div>
            </div>
            <div class="area">
              <div class="title">
                <img src="/src/assets/images/acidRolling/title-icon.png" />
                <span>雷达图标题</span>
              </div>
              <div style="height: 22vh">
                <graph-radar />
              </div>
            </div>
            <div class="area">
              <div class="title">
                <img src="/src/assets/images/acidRolling/title-icon.png" />
                <span>雷达图标题</span>
              </div>
              <div style="height: 22vh">
                <graph-radar />
              </div>
            </div>
            <div class="area"
              style="display: flex; flex-direction: column; justify-content: space-around; gap: 1.5vh; padding: 1vh 0.5vw;">
              <!-- 第1行：日产数据 -->
              <div style="display: flex; flex-direction: column; align-items: center; gap: 0.8vh;">
                <img src="/src/assets/images/acidRolling/prod-day.png" style="width: 2.5vw; height: auto;" />
                <div style="display: flex; justify-content: space-around; width: 100%; gap: 0.7vw;">
                  <div class="prod-item">
                    <span class="data">{{ numberFormat(dailyProduction) }}</span>
                    <span class="data-text">日产量(吨)</span>
                  </div>
                  <div class="prod-item">
                    <span class="data">{{ numberFormat(dailyTopProd) }}</span>
                    <span class="data-text">日产记录(吨)</span>
                  </div>
                </div>
              </div>

              <!-- 第2行：月产数据 -->
              <div style="display: flex; flex-direction: column; align-items: center; gap: 0.8vh;">
                <img src="/src/assets/images/acidRolling/prod-month.png" style="width: 2.5vw; height: auto;" />
                <div style="display: flex; justify-content: space-around; width: 100%; gap: 0.7vw;">
                  <div class="prod-item">
                    <span class="data">{{numberFormat(monthProduction) }}</span>
                    <span class="data-text">月产量(吨)</span>
                  </div>
                  <div class="prod-item">
                    <span class="data">{{numberFormat(monthTopProd) }}</span>
                    <span class="data-text">月产记录(吨)</span>
                  </div>
                </div>
              </div>

              <!-- 第3行：设定数据 -->
              <div style="display: flex; flex-direction: column; align-items: center; gap: 0.8vh;">
                <img src="/src/assets/images/acidRolling/prod-set.png" style="width: 2.5vw; height: auto;" />
                <div style="display: flex; justify-content: space-around; width: 100%; gap: 0.1vw;">
                  <div class="prod-item">
                    <span class="data">{{numberFormat(monthSet) }}</span>
                    <span class="data-text">月设定产量(吨)</span>
                  </div>
                  <div class="prod-item">
                    <span class="data">{{numberFormat(monthRate) }}</span>
                    <span class="data-text">月完成率(%)</span>
                  </div>
                </div>
              </div>
            </div>
            <div class="area">
              <div class="title">
                <img src="/src/assets/images/acidRolling/title-icon.png" />
                <span>活套套量</span>
              </div>
              <!-- 最大设定值显示 -->
              <div class="arpe-chart-legend" style="
                  font-size: 13px;
                  text-align: left;
                  margin-top: 2px;
                  margin-left: 18px;
                  margin-bottom: 10px;
                  letter-spacing: 2px;
                  display: flex;
                  align-items: center;
                  justify-content: flex-start;
                ">
                <span style="color: #00eaff; font-weight: bold;">max:</span>
                <span style="color: #fff; font-size: 15px; font-weight: bold; flex: 1; text-align: center">
                  {{ exportLooperMaxSet }}&nbsp;&nbsp;&nbsp;&nbsp;{{ middleLooperMaxSet }}&nbsp;&nbsp;&nbsp;&nbsp;{{
                    inletLooperMaxSet }}
                </span>
              </div>
              <!-- 最小设定值显示 -->
              <div class="arpe-chart-legend" style="
                  font-size: 13px;
                  text-align: left;
                  margin-top: 2px;
                  margin-left: 18px;
                  margin-bottom: 20px;
                  letter-spacing: 2px;
                  display: flex;
                  align-items: center;
                  justify-content: flex-start;
                ">
                <span style="color: #00eaff; font-weight: bold;">min:</span>
                <span style="color: #fff; font-size: 15px; font-weight: bold; flex: 1; text-align: center">
                  23&nbsp;&nbsp;&nbsp;&nbsp;25&nbsp;&nbsp;&nbsp;&nbsp;27
                </span>
              </div>
              <div id="bar1" class="arpe-chart" style="height: 22vh; margin-top: -2vh"></div>
            </div>
            <div class="area pie-info">
              <div class="title">
                <img src="/src/assets/images/acidRolling/title-icon.png" />
                <span>焊机时序跟踪</span>
              </div>
              <div style="display: flex; flex-wrap: nowrap; justify-content: center; align-items: baseline; gap: 0.5vw">
                <span class="sub-t">{{ welderCurrentStep.stepName }}</span>
                <span class="main-t">{{ welderCurrentStep.countdown }}s</span>
              </div>
              <div style="height: 20vh">
                <graph-pie :data="welderPieSeries" />
              </div>
              <span class="sub-t" style="display: flex; justify-content: center; align-items: center">{{ welderCoilNo ||
                '-' }}</span>
            </div>
            <div class="area pie-info">
              <div class="title">
                <img src="/src/assets/images/acidRolling/title-icon.png" />
                <span>2#开卷机时序跟踪</span>
              </div>
              <div style="display: flex; flex-wrap: nowrap; justify-content: center; align-items: baseline; gap: 0.5vw">
                <span class="sub-t">{{ uncoiler2CurrentStep.stepName }}</span>
                <span class="main-t">{{ uncoiler2CurrentStep.countdown }}s</span>
              </div>
              <div style="height: 20vh">
                <graph-pie :data="uncoiler2PieSeries" />
              </div>
              <span class="sub-t" style="display: flex; justify-content: center; align-items: center">{{ por2CoilNo ||
                '-' }}</span>
            </div>
            <div class="area pie-info">
              <div class="title">
                <img src="/src/assets/images/acidRolling/title-icon.png" />
                <span>1#开卷机时序跟踪</span>
              </div>
              <div style="display: flex; flex-wrap: nowrap; justify-content: center; align-items: baseline; gap: 0.5vw">
                <span class="sub-t">{{ uncoiler1CurrentStep.stepName }}</span>
                <span class="main-t">{{ uncoiler1CurrentStep.countdown }}s</span>
              </div>
              <div style="height: 20vh">
                <graph-pie :data="uncoiler1PieSeries" />
              </div>
              <span class="sub-t" style="display: flex; justify-content: center; align-items: center">{{ por1CoilNo ||
                '-' }}</span>
            </div>
          </div>
          <div class="areas2">
            <div class="area areas2-garph1">
              <div class="title">
                <img src="/src/assets/images/acidRolling/title-icon.png" />
                <span>实时数据</span>
              </div>
              <!-- 柱状图区域（上半部分，占75%） -->
              <div class="realtime-chart-container">
                <graph-bar-line :datax="realTimeData?.stand" :data-bar1="realTimeData?.data1"
                  :data-bar2="realTimeData?.data2" :data-bar3="realTimeData?.dataFGC" :data-bar4="realTimeData?.dataAGC"
                  :bar-name="['功率实际值', '电机扭矩实际值', 'FGC', 'AGC']" :y-axis-name="['', '']" :legend-pos="8" :max-y="50" />
              </div>
              <!-- 列表区域（下半部分，占25%） -->
              <div class="realtime-table-container">
                <el-table 
                  :data="realTimeDataList" 
                  :header-cell-style="{ background: '#2f59af', color: '#fff', fontSize: '12px', border: 'none' }"
                  :cell-style="{ fontSize: '11px', color: 'rgba(255, 255, 255, 0.7)' }"
                  height="100%"
                  style="width: 100%">
                  <el-table-column prop="chinese" label="" width="120" align="left"/>
                  <el-table-column prop="5" label="5#机架" align="center"/>
                  <el-table-column prop="4" label="4#机架" align="center"/>
                  <el-table-column prop="3" label="3#机架" align="center"/>
                  <el-table-column prop="2" label="2#机架" align="center"/>
                  <el-table-column prop="1" label="1#机架" align="center"/>
                </el-table>
              </div>
            </div>
            <div class="area plan-prod">
              <!-- 日计划下达产量 -->
              <div style="display: flex; flex-direction: column; align-items: center; gap: 8px">
                <div style="position: relative">
                  <!-- 上方数值显示：dayPlan（橙黄色） -->
                  <div style="
                      position: absolute;
                      top: -25px;
                      left: 50%;
                      transform: translateX(-50%);
                      color: #ffa500;
                      font-size: 14px;
                      font-weight: 700;
                      white-space: nowrap;
                      text-shadow: 0 0 8px rgba(255, 165, 0, 0.6);
                    ">
                    {{ dayPlan > 0 ? Math.floor(dayPlan) : '0' }}
                  </div>
                  <div style="
                      width: 54px;
                      height: 170px;
                      border: 2px solid rgba(0, 234, 255, 0.6);
                      border-radius: 12px;
                      background: rgba(0, 24, 48, 0.35);
                      box-shadow: inset 0 0 14px rgba(0, 234, 255, 0.18);
                      padding: 4px;
                      display: flex;
                      align-items: flex-end;
                      justify-content: center;
                      position: relative;
                    ">
                    <div :style="{
                      width: '100%',
                      height: Math.max(0, Math.min(100, dayPlanRate)) + '%',
                      background: 'linear-gradient(180deg, rgba(0,246,255,0.95) 0%, rgba(0,246,255,0.35) 100%)',
                      borderRadius: '8px',
                      boxShadow: '0 0 10px rgba(0,246,255,0.35)',
                      position: 'relative',
                      display: 'flex',
                      flexDirection: 'column',
                      alignItems: 'center',
                      justifyContent: 'center',
                    }">
                      <!-- 柱状图内数值显示：dayPlanXiada（橙黄色）和 dayPlanRate%（橙黄色） -->
                      <div
                        style="color: #ffa500; font-size: 14px; font-weight: 700; text-shadow: 0 0 8px rgba(255, 165, 0, 0.6); line-height: 1.2;">
                        {{ dayPlanXiada > 0 ? Math.floor(dayPlanXiada) : '0' }}
                      </div>
                      <div
                        style="color: #ffa500; font-size: 14px; font-weight: 700; text-shadow: 0 0 8px rgba(255, 165, 0, 0.6); line-height: 1.2;">
                        {{ Math.floor(dayPlanRate) }}%
                      </div>
                    </div>
                  </div>
                </div>
                <div style="color: #b2eaff; font-size: 12px; text-align: center; line-height: 1.2; width: 120px">日计划下达产量
                </div>
              </div>

              <!-- 日计划产量累计达成率 -->
              <div style="display: flex; flex-direction: column; align-items: center; gap: 8px">
                <div style="position: relative">
                  <!-- 上方数值显示：dayPlan（橙黄色）和 (100%)（橙黄色，固定值） -->
                  <div style="
                      position: absolute;
                      top: -25px;
                      left: 50%;
                      transform: translateX(-50%);
                      color: #ffa500;
                      font-size: 14px;
                      font-weight: 700;
                      white-space: nowrap;
                      text-shadow: 0 0 8px rgba(255, 165, 0, 0.6);
                      display: flex;
                      gap: 8px;
                      align-items: center;
                    ">
                    <span>{{ dayPlan > 0 ? Math.floor(dayPlan) : '0' }}</span>
                    <span>(100%)</span>
                  </div>
                  <div style="
                      width: 54px;
                      height: 170px;
                      border: 2px solid rgba(82, 196, 26, 0.6);
                      border-radius: 12px;
                      background: rgba(0, 24, 48, 0.35);
                      box-shadow: inset 0 0 14px rgba(82, 196, 26, 0.18);
                      padding: 4px;
                      display: flex;
                      align-items: flex-end;
                      justify-content: center;
                      position: relative;
                    ">
                    <div :style="{
                      width: '100%',
                      height: Math.max(0, dayActRate) + '%',
                      background: 'linear-gradient(180deg, rgba(82,196,26,0.95) 0%, rgba(82,196,26,0.35) 100%)',
                      borderRadius: '8px',
                      boxShadow: '0 0 10px rgba(82,196,26,0.35)',
                      position: 'relative',
                      display: 'flex',
                      flexDirection: 'column',
                      alignItems: 'center',
                      justifyContent: 'center',
                    }">
                      <!-- 柱状图内数值显示：dayAct（橙黄色）和 dayActRate%（橙黄色） -->
                      <div
                        style="color: #ffa500; font-size: 14px; font-weight: 700; text-shadow: 0 0 8px rgba(255, 165, 0, 0.6); line-height: 1.2;">
                        {{ dayAct > 0 ? Math.floor(dayAct) : '0' }}
                      </div>
                      <div
                        style="color: #ffa500; font-size: 14px; font-weight: 700; text-shadow: 0 0 8px rgba(255, 165, 0, 0.6); line-height: 1.2;">
                        {{ Math.floor(dayActRate) }}%
                      </div>
                    </div>
                  </div>
                </div>
                <div style="color: #b2eaff; font-size: 12px; text-align: center; line-height: 1.2; width: 120px">
                  日计划产量累计达成率</div>
              </div>
            </div>
            <div class="area areas2-garph1">
              <div class="title">
                <img src="/src/assets/images/acidRolling/title-icon.png" />
                <span>产量</span>
              </div>
              <div class="swtichDate">
                <!-- text-color="#626aef" fill="rgb(239, 240, 253)" class="radio-right" -->
                <el-radio-group v-model="radio" size="small" @change="fetchMillUnitBarData">
                  <el-radio-button label="小时" value="hour" />
                  <el-radio-button label="天" value="day" />
                </el-radio-group>
              </div>
              <div ref="productionChartRef" style="height: 25vh; margin-top: 0.5vh;width: 96%;"></div>
            </div>
          </div>
          <div class="status-info">
            <div class="info-item" style="width: 8vw" @click="handleStatusCardClick('异常设备状态')">
              <div class="item-bg">
                <img src="/src/assets/images/acidRolling/item-bg1.png" />
              </div>
              <div class="item-icon">
                <img src="/src/assets/images/acidRolling/item-icon1.png" />
              </div>
              <div class="item-text">
                <span>异常设备状态</span>
              </div>
            </div>
            <div class="info-item" style="width: 8vw" @click="handleStatusCardClick('停机信息录入')">
              <div class="item-bg">
                <img src="/src/assets/images/acidRolling/item-bg1.png" />
              </div>
              <div class="item-icon">
                <img src="/src/assets/images/acidRolling/item-icon2.png" />
              </div>
              <div class="item-text">
                <span>停机信息录入</span>
              </div>
            </div>
            <div class="info-item" style="width: 7vw" @click="handleStatusCardClick('换辊统计')">
              <div class="item-bg">
                <img src="/src/assets/images/acidRolling/item-bg1.png" />
              </div>
              <div class="item-icon">
                <img src="/src/assets/images/acidRolling/item-icon3.png" />
              </div>
              <div class="item-text">
                <span>换辊统计</span>
              </div>
            </div>
            <div class="info-item" style="width: 7vw" @click="handleStatusCardClick('重焊统计')">
              <div class="item-bg">
                <img src="/src/assets/images/acidRolling/item-bg1.png" />
              </div>
              <div class="item-icon">
                <img src="/src/assets/images/acidRolling/item-icon4.png" />
              </div>
              <div class="item-text">
                <span>重焊统计</span>
              </div>
            </div>
            <div class="info-item" style="width: 8vw" @click="handleStatusCardClick('异常剪切状态')">
              <div class="item-bg">
                <img src="/src/assets/images/acidRolling/item-bg1.png" />
              </div>
              <div class="item-icon">
                <img src="/src/assets/images/acidRolling/item-icon5.png" />
              </div>
              <div class="item-text">
                <span>异常剪切状态</span>
              </div>
            </div>
            <div class="info-item" style="width: 9vw" @click="handleStatusCardClick('开卷机异常统计')">
              <div class="item-bg">
                <img src="/src/assets/images/acidRolling/item-bg1.png" />
              </div>
              <div class="item-icon">
                <img src="/src/assets/images/acidRolling/item-icon6.png" />
              </div>
              <div class="item-text">
                <span>开卷机异常统计</span>
              </div>
            </div>
            <div class="prod-info">
              <img src="/src/assets/images/acidRolling/prod-day.png" />
              <div class="prod-item">
                <span class="data">{{ numberFormat(dailyProduction) }}</span>
                <span class="data-text">日产量(吨)</span>
              </div>
              <div class="prod-item">
                <span class="data">{{ numberFormat(dailyTopProd) }}</span>
                <span class="data-text">日产记录(吨)</span>
              </div>
            </div>
            <div class="prod-info">
              <img src="/src/assets/images/acidRolling/prod-month.png" />
              <div class="prod-item">
                <span class="data">{{ numberFormat(monthProduction) }}</span>
                <span class="data-text">月产量(吨)</span>
              </div>
              <div class="prod-item">
                <span class="data">{{ numberFormat(monthTopProd) }}</span>
                <span class="data-text">月产记录(吨)</span>
              </div>
            </div>
            <div class="prod-info">
              <img src="/src/assets/images/acidRolling/prod-set.png" />
              <div class="prod-item">
                <span class="data">{{ numberFormat(monthSet) }}</span>
                <span class="data-text">月设定产量(吨)</span>
              </div>
              <div class="prod-item">
                <span class="data">{{ numberFormat(monthRate) }}</span>
                <span class="data-text">月完成率(%)</span>
              </div>
            </div>
          </div>
        </div>
        <div class="coils">
          <div v-for="index in 13" :key="index"><img src="/src/assets/images/acidRolling/coil-green.png" /></div>
        </div>
      </div>
    </div>
  </div>
  <!-- 辊位图弹窗 -->
  <el-dialog
    v-model="rollDetailsVisible"
    title="辊位图详情"
    width="90%"
    top="5vh"
    :close-on-press-escape="true"
    class="roll-details-dialog"
    modal-class="roll-details-mask"
    :z-index="999"
    :style="{
      '--el-dialog-bg-color': 'rgba(10, 24, 48, 0.98)',
      '--el-bg-color': 'rgba(10, 24, 48, 0.98)',
      '--el-bg-color-overlay': 'rgba(10, 24, 48, 0.98)',
      background: 'rgba(10, 24, 48, 0.98) !important',
      border: '2px solid #00f6ff',
      borderRadius: '16px',
      boxShadow: '0 0 40px rgba(0, 246, 255, 0.4), inset 0 0 20px rgba(0, 246, 255, 0.1)',
      backdropFilter: 'blur(15px)',
      zIndex: '999'
    }"
  >
    <div
      style="
        width: 100%;
        height: 80vh;
        background: rgba(28, 58, 99, 0.7);
        border: 1px solid rgba(90, 130, 190, 0.4);
        border-radius: 8px;
        box-shadow: 0 0 10px rgba(11, 93, 209, 0.15);
        display: flex;
        align-content: center;
        justify-content: center;
        padding: 14px;
      "
    >
      <RollPosImage2280 r-group="5703/2280酸轧机组" svg-url="/rollPosImage/2280.svg" style="width: 100%; flex-grow: 1" />
    </div>
  </el-dialog>
</template>
<script lang="ts" setup>
import GraphRadar from './components/GraphRadar.vue';
import GraphBar from './components/GraphBar.vue';
import GraphBarLine from './components/GraphBarLine.vue';
import GraphPie from './components/GraphPie.vue';
import RollPosImage2280 from '/@/views/common/RollPosImage/2280RollPosImage.vue';
import { onMounted, onUnmounted, nextTick, ref, computed, reactive, defineComponent, h, watch, onBeforeMount } from 'vue';
import { useRouter } from 'vue-router';
import { refreshSVG, initialSVG, refreshGraphical } from '/@/common/refreshSVG';
import { rollingSimulationApi } from '/@/api/RollingSimulation/index';
import axios from 'axios';
import { weldMachineState, rollStateFun } from '/@/views/common/FulllineTrack/full.line.track.status';
import { sleeveDeclineTime, SearchForCoidId } from '/@/views/common/FulllineTrack/full.line.track.handle';
import { rollingMillStatusHandel } from '/@/views/common/FulllineTrack/RollingMillVibration';
import { outputAnalysisApi } from '/@/api/report/TCM2208MillUnit/index';
import { acidRollingApi } from '/@/api/acidRollingProductionEfficiency/index';
import { useUserStore } from '/@/store/modules/system/user';
import * as echarts from 'echarts';
import dayjs from 'dayjs';

// TCMTrackInfo 组件 - 简单占位符组件
const TCMTrackInfo = defineComponent({
  name: 'TCMTrackInfo',
  props: {
    infoData: {
      type: Object,
      default: () => ({}),
    },
  },
  setup(props) {
    return () =>
      h('div', { style: 'color: #fff; text-align: center; padding: 0.5vh' }, [
        h('div', { style: 'font-size: 1.2vw; font-weight: bold' }, props.infoData?.value || 0),
        h('div', { style: 'font-size: 0.8vw' }, props.infoData?.title || ''),
      ]);
  },
});

const controller = new AbortController();
const router = useRouter();

const data = ref([
  { menuName: 'acidRollingProductionEfficiencys', menuTitle: '酸轧生产效率主页', menuId: '1' },
  // { menuName: 'indexY', menuTitle: '主页 改' },
  { menuName: 'singleRollProductionEfficiencyAnalysis', menuTitle: '单卷生产效率分析评价' },
  { menuName: 'reWeldingFrequencyTraceability', menuTitle: '重焊次数追溯' },
  { menuName: 'shutdownStatistics', menuTitle: '停机明细及统计' },
  { menuName: 'productionschedulereport', menuTitle: '生产时序统计' },
  { menuName: 'productionspeed', menuTitle: '轧机速度未达成率' },
  { menuName: 'analysisdiagnosis', menuTitle: '生产效率分析诊断' },
  { menuName: 'rollchange', menuTitle: '换辊明细' },
  { menuName: 'rollingSpeed', menuTitle: '酸轧工艺限速维护' },
  { menuName: 'rollingSpeedCopy', menuTitle: '酸轧工艺限速维护(复)' },
]);

const realTimeData = reactive({
  stand: ['1#', '2#', '3#', '4#', '5#'],
  data1: [100, 100, 100, 100, 100],
  data2: [100, 100, 100, 100, 100],
  dataFGC: [0, 0, 0, 0, 0], // FGC数据
  dataAGC: [0, 0, 0, 0, 0], // AGC数据
});

// 实时数据列表（用于表格显示 - 轧制力三行格式）
const realTimeDataList = computed(() => {
  if (!realTimeData.stand || !realTimeData.dataFGC || !realTimeData.dataAGC) {
    return [
      { chinese: 'Current(real)', '5': '0', '4': '0', '3': '0', '2': '0', '1': '0' },
      { chinese: 'Next(set up)', '5': '0', '4': '0', '3': '0', '2': '0', '1': '0' },
      { chinese: 'Difference', '5': 0, '4': 0, '3': 0, '2': 0, '1': 0 }
    ];
  }
  
  // Current(real) 行 - 当前实际轧制力（AGC）
  const currentRow: any = { chinese: 'Current(real)' };
  // Next(set up) 行 - 下一卷设定轧制力（FGC）
  const nextRow: any = { chinese: 'Next(set up)' };
  // Difference 行 - 差值
  const diffRow: any = { chinese: 'Difference' };
  
  realTimeData.stand.forEach((stand, index) => {
    const standNum = stand.replace('#机架', '').replace('机架', '');
    const current = Math.round(realTimeData.dataAGC[index] || 0);
    const next = Math.round(realTimeData.dataFGC[index] || 0);
    const diff = current - next;
    
    currentRow[standNum] = current.toString();
    nextRow[standNum] = next.toString();
    diffRow[standNum] = diff;
  });
  
  return [currentRow, nextRow, diffRow];
});

// 产量图表引用
const productionChartRef = ref<HTMLElement | null>(null);
let productionChartInstance: echarts.ECharts | null = null;

const technologicalName = 'TCM2280';
const radio = ref('day'); // 默认显示"天"的数据
const pieCountdown = ref(150);

interface PieDataItem {
  name: string;
  value: number;
  realValue: number | null;
  standard?: number | null;
  itemStyle?: Record<string, any>;
}

const diffTimeStandard = ref<Record<string, any>>({});
const welderPieSeries = ref<any>([[]]);
const uncoiler1PieSeries = ref<any>([[]]);
const uncoiler2PieSeries = ref<any>([[]]);
const por1CoilNo = ref('');
const por2CoilNo = ref('');
const welderCoilNo = ref('');

// 时序跟踪当前步骤信息
interface CurrentStepInfo {
  stepName: string;
  standardTime: number;
  countdown: number;
  startTime: number | null;
  step: number; // 步骤号：1-装卷 2-开卷 3-穿卷 4-切头
}

const welderCurrentStep = ref<CurrentStepInfo>({
  stepName: '-',
  standardTime: 0,
  countdown: 0,
  startTime: null,
  step: 0,
});

const uncoiler1CurrentStep = ref<CurrentStepInfo>({
  stepName: '-',
  standardTime: 0,
  countdown: 0,
  startTime: null,
  step: 0,
});

const uncoiler2CurrentStep = ref<CurrentStepInfo>({
  stepName: '-',
  standardTime: 0,
  countdown: 0,
  startTime: null,
  step: 0,
});

// 保存上一次的数据快照，用于判断步骤是否完成
const lastWelderData = ref<Record<string, any> | null>(null);
const lastUncoiler1Data = ref<Record<string, any> | null>(null);
const lastUncoiler2Data = ref<Record<string, any> | null>(null);

interface SvgInfo {
  extAISet: null | number;
  extAISetFlag: null | number;
  extSpeed: null | number;
  entRollingMillSpeed: null | number;
  crossCuttingShears1: null | number;
  crossCuttingShears2: null | number;
  crossCuttingShears1Actual: null | number; // 1#横切剪实际切头米数
  crossCuttingShears2Actual: null | number; // 2#横切剪实际切头米数
  residualTime: null | number;
  residualPlanTime: null | number;
  discShearSpeed: null | number;
  dryerTemp: null | number;
  craftAISet: null | number;
  craftAISetFlag: null | number;
  craftSpeed: null | number;
  entAISet: null | number;
  entAISetFlag: null | number;
  entSpeed: null | number;
  extDownForce1: null | number;
  extDownForce2: null | number;
  extDownForce3: null | number;
  extDownForce4: null | number;
  entDownForce1: null | number;
  entDownForce2: null | number;
  entDownForce3: null | number;
  entDownForce4: null | number;
  // 1#矫直机压下量
  straightener1EntSet: null | number; // 1#矫直机压下量入口设定
  straightener1EntFbk: null | number; // 1#矫直机压下量入口反馈
  straightener1ExtSet: null | number; // 1#矫直机压下量出口设定
  straightener1ExtFbk: null | number; // 1#矫直机压下量出口反馈
  // 2#矫直机压下量
  straightener2EntSet: null | number; // 2#矫直机压下量入口设定
  straightener2EntFbk: null | number; // 2#矫直机压下量入口反馈
  straightener2ExtSet: null | number; // 2#矫直机压下量出口设定
  straightener2ExtFbk: null | number; // 2#矫直机压下量出口反馈
  // 拉矫机模式
  levelerAutoMode: null | number; // 拉矫机自动模式
  levelerManualMode: null | number; // 拉矫机手动模式
  trLength1: null | number;
  trLength2: null | number;
}
const svgInfo = reactive<SvgInfo>({
  // 出口段
  extAISet: 0,
  extAISetFlag: 0,
  extSpeed: 0,
  entRollingMillSpeed: 0,
  crossCuttingShears1: 0,
  crossCuttingShears2: 0,
  crossCuttingShears1Actual: 0, // 1#横切剪实际切头米数
  crossCuttingShears2Actual: 0, // 2#横切剪实际切头米数
  residualTime: 0,
  residualPlanTime: 0,
  discShearSpeed: 0,
  dryerTemp: 0,
  // 工艺段
  craftAISet: 0,
  craftAISetFlag: 0,
  craftSpeed: 0,
  // 入口段
  entAISet: 0,
  entAISetFlag: 0,
  entSpeed: 0,
  // 矫直机下压量
  extDownForce1: 0,
  extDownForce2: 0,
  extDownForce3: 0,
  extDownForce4: 0,
  entDownForce1: 0,
  entDownForce2: 0,
  entDownForce3: 0,
  entDownForce4: 0,
  // 1#矫直机压下量
  straightener1EntSet: 0,
  straightener1EntFbk: 0,
  straightener1ExtSet: 0,
  straightener1ExtFbk: 0,
  // 2#矫直机压下量
  straightener2EntSet: 0,
  straightener2EntFbk: 0,
  straightener2ExtSet: 0,
  straightener2ExtFbk: 0,
  // 拉矫机模式
  levelerAutoMode: 0,
  levelerManualMode: 0,
  // 开卷机剩余长度
  trLength1: 0,
  trLength2: 0,
});

// 辊位图弹窗相关
const rollDetailsVisible = ref(false);
const currentRollData = ref({
  rGroup: '5703/2280酸轧机组',
  svgUrl: '/rollPosImage/2280.svg',
});
const svgContainer = ref<HTMLElement | null>(null);

// 监听 rollDetailsVisible 的变化
watch(rollDetailsVisible, (newVal) => {
  console.log('rollDetailsVisible 变化:', newVal);
});

// 打开辊位图弹窗
function openRollDetails(rollData?: any) {
  console.log('openRollDetails 被调用，参数:', rollData);
  if (rollData) {
    // 如果传入了辊子数据，更新当前数据
    currentRollData.value = {
      rGroup: rollData.rGroup || '5703/2280酸轧机组',
      svgUrl: '/rollPosImage/2280.svg',
    };
    console.log('更新 currentRollData:', currentRollData.value);
  }
  rollDetailsVisible.value = true;
  console.log('设置 rollDetailsVisible 为 true');
}

// 绑定 SVG 辊子点击事件
function bindSvgRollClickEvents() {
  if (!svgContainer.value) return;

  // 由于 svg-load 使用 SVG sprite，我们需要等待 SVG symbol 被加载
  // 使用轮询方式检查 SVG 内容是否已经渲染
  const checkSvgContent = () => {
    const svgElement = svgContainer.value?.querySelector('svg');
    if (svgElement) {
      // 检查是否有实际的 SVG 内容（不仅仅是空的 use 标签）
      const useElement = svgElement.querySelector('use');
      if (useElement) {
        // 检查 SVG symbol 是否已经被加载到页面中
        const symbolId = useElement.getAttribute('xlink:href') || useElement.getAttribute('href');
        if (symbolId) {
          const symbolElement = document.querySelector(symbolId);
          if (symbolElement) {
            console.log('SVG symbol 已加载:', symbolId);
            // 等待一小段时间确保 SVG symbol 被完全加载
            setTimeout(() => {
              bindClickEventsToSvg(svgElement);
            }, 200);
            return true;
          } else {
            console.log('SVG symbol 未找到:', symbolId);
          }
        }
      }
    }
    return false;
  };

  // 如果立即检查失败，则使用轮询
  if (!checkSvgContent()) {
    console.log('开始轮询检查 SVG 内容...');
    const interval = setInterval(() => {
      if (checkSvgContent()) {
        clearInterval(interval);
      }
    }, 100);

    // 设置最大等待时间，避免无限轮询
    setTimeout(() => {
      clearInterval(interval);
      console.log('SVG 加载超时，尝试直接绑定事件');
      // 即使超时也尝试绑定事件
      const svgElement = svgContainer.value?.querySelector('svg');
      if (svgElement) {
        bindClickEventsToSvg(svgElement);
      }
    }, 5000);
  }
}

// 为 SVG 元素绑定点击事件
function bindClickEventsToSvg(svgElement: SVGElement) {
  console.log('开始绑定 SVG 点击事件');

  // 直接给整个 SVG 元素添加点击事件
  svgElement.style.cursor = 'pointer';
  svgElement.addEventListener('click', (event) => {
    event.stopPropagation();
    console.log('点击了 SVG 图');

    // 获取点击位置的信息
    const rect = svgElement.getBoundingClientRect();
    const x = event.clientX - rect.left;
    const y = event.clientY - rect.top;

    console.log('点击位置:', { x, y });
    console.log('准备调用 openRollDetails...');

    // 调用弹窗函数，传入默认参数
    openRollDetails({
      line: 'SVG点击',
      rGroup: '5703/2280酸轧机组',
      area: 'SVG区域',
      pos: `(${Math.round(x)}, ${Math.round(y)})`,
      rType: 'SVG点击',
    });

    console.log('openRollDetails 调用完成');
  });

  console.log('SVG 整体点击事件绑定完成');
}

const coilIdCountMap = ref<Map<string, number>>(new Map<string, number>());
const coilTotalCount = computed(() => {
  if (coilIdCountMap.value.size === 0) return 0;
  return Array.from(coilIdCountMap.value.values()).reduce((total, current) => total + current, 0);
});
const acidLevels = ref([0, 0, 0]); // 酸槽液位：1#、2#、3#
const acidTemps = ref([0, 0, 0]); // 酸槽温度：1#、2#、3#
const getWidth = (entid: string) => {
  const count = coilIdCountMap.value.get(entid) || 0;
  return (count * 100) / coilTotalCount.value || 0;
};

// 计算柱子的高度百分比，基于最大值
const getBarHeight = (value: number) => {
  if (!acidLevels.value || acidLevels.value.length === 0) {
    return 0;
  }
  const maxValue = Math.max(...acidLevels.value);
  if (maxValue === 0) {
    return 0;
  }
  // 计算高度百分比，最大高度为90%，给上方留出空隙，最小高度为10%
  const percentage = (value / maxValue) * 90; // 最大90%，留出10%的空隙
  return Math.max(10, Math.min(90, percentage));
};

// left: `${getBarLeftPosition(coilInfo, item)}%`,
// 计算颜色条的left位置，基于前面所有颜色条的累计宽度
// const getBarLeftPosition = (items: any[], currentItem: any) => {
//   const currentIndex = items.findIndex((item) => item.extId === currentItem.extId);
//   if (currentIndex === -1 || currentIndex === 0) {
//     return 0;
//   }
//   // 计算前面所有颜色条的百分比之和
//   let leftPosition = 0;
//   for (let i = 0; i < currentIndex; i++) {
//     leftPosition += items[i].barPercentage || 0;
//   }
//   return leftPosition;
// };

// ---------------------------------------------------  数据对接 ---------------------------------------------------

// 统一管理定时器
const timers = {
  main: null as NodeJS.Timeout | null,
  warning: null as NodeJS.Timeout | null,
  ai: null as NodeJS.Timeout | null,
  por: null as NodeJS.Timeout | null,
  coilRunTime: null as NodeJS.Timeout | null, // 剩余时长定时器（每秒）
  sequenceCountdown: null as NodeJS.Timeout | null, // 时序跟踪倒计时定时器（每秒）
};

onBeforeMount(() => {
  useUserStore().setTagNav(data.value);
});

onMounted(() => {
  timers.warning = setInterval(() => {
    pieCountdown.value -= 1;
  }, 1000);

  // 时序跟踪倒计时定时器（每秒更新）
  timers.sequenceCountdown = setInterval(() => {
    // 更新1#开卷机倒计时（每秒减1，可为负数）
    if (uncoiler1CurrentStep.value.step > 0) {
      uncoiler1CurrentStep.value.countdown -= 1;
    }
    // 更新2#开卷机倒计时（每秒减1，可为负数）
    if (uncoiler2CurrentStep.value.step > 0) {
      uncoiler2CurrentStep.value.countdown -= 1;
    }
  }, 1000);

  // 初始数据加载
  getZoneTrk();
  fetchAISetValues();
  fetchGaugeData();
  getSteelInfo();
  getHourSpeed();
  getRollingMillVibration(); // 获取轧机震动数据
  fetchDiffTimeStandard();

  // 获取产量相关数据（按照 index old.vue 的方式）
  fetchMillUnitBarData(); // 获取产量图表数据
  fetchOutputPlanAct(); // 获取日计划下达产量和达成率数据（新接口）
  fetchTcmOutputRecord(); // 获取日产量、日产记录、月产量、月产记录、月设定产量、月完成率数据
  fetchSequenceTrackingData(); // 获取焊机/开卷机时序跟踪数据

  // 初始化速度仪表盘和活套套量柱状图
  nextTick(() => {
    initScoreChart('middle_speed1', extSpeed.value);
    initScoreChart('middle_speed2', entSpeed.value);
    initScoreChart('middle_speed4', tcmSpeed.value);
    initScoreChart('middle_speed5', ypjSpeed.value);
    // middle_speed6 已改为白色字体显示，不需要仪表盘
    // initScoreChart('middle_speed6', mill_enter_speed.value);

    // 初始化活套套量柱状图（按照 index old.vue 的方式）
    initLooperBarChart();

    // 初始化产量图表（按照 index old.vue 的方式）
    initProductionChart();

    // 绑定 SVG 辊位点击事件
    bindSvgRollClickEvents();
  });

  // 添加窗口大小变化监听
  window.addEventListener('resize', handleProductionChartResize);

  // 定时更新（轧机颜色变化在 getZoneTrk 中通过 segmentStop 处理）
  timers.ai = setInterval(() => {
    getZoneTrk();
    fetchAISetValues();
    fetchGaugeData();
    getSteelInfo();
    getHourSpeed();
    getRollingMillVibration(); // 定时获取轧机震动数据
    fetchMillUnitBarData(); // 定时更新产量图表数据
    fetchOutputPlanAct(); // 定时更新日计划下达产量和达成率数据（新接口）
    fetchTcmOutputRecord(); // 定时更新日产量、日产记录、月产量、月产记录、月设定产量、月完成率数据
    fetchSequenceTrackingData(); // 定时更新焊机/开卷机时序跟踪数据
  }, 5000);

  // 定时更新剩余时长（暂时注释：接口未开发）
  // timers.coilRunTime = setInterval(() => {
  //   getCoilRunTime();
  // }, 1000);

  // 定时更新剩余时长（每秒）
  timers.coilRunTime = setInterval(() => {
    getCoilRunTime();
  }, 1000);
});

onUnmounted(() => {
  // 清理定时器
  Object.values(timers).forEach((timer) => {
    if (timer) {
      clearInterval(timer);
    }
  });
  controller.abort();

  // 移除窗口大小变化监听
  window.removeEventListener('resize', handleProductionChartResize);

  // 清理产量图表实例
  if (productionChartInstance) {
    productionChartInstance.dispose();
    productionChartInstance = null;
  }
});

// API重试机制
async function fetchDataWithRetry(apiCall: () => Promise<any>, maxRetries = 3, delay = 1000): Promise<any> {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await apiCall();
    } catch (error: any) {
      if (axios.isCancel(error)) {
        throw error; // 如果是取消请求，直接抛出
      }
      if (i === maxRetries - 1) {
        console.error(`API调用失败，已重试${maxRetries}次:`, error);
        throw error;
      }
      console.warn(`API调用失败，${delay * (i + 1)}ms后重试 (${i + 1}/${maxRetries}):`, error.message);
      await new Promise((resolve) => setTimeout(resolve, delay * (i + 1)));
    }
  }
}

const coilColorMap = ref<any>({});
const coilIds = ref([]);
const coilInfo = ref<any>([]);
const inletLooper = ref<number>(0);
const middleLooper = ref<number>(0);
const exportLooper = ref<number>(0);
let tr: any = null;
let por: any = null;
let ti: any = null;

// 新增：各段停止状态
const entStop = ref<boolean>(false);
const tchStop = ref<boolean>(false);
const cirStop = ref<boolean>(false);
const rollStop = ref<boolean>(false);

// 活套套量柱形图
const looperData = ref<Number[]>([]);

// 新增：活套时间
const inletLooperTime = ref<string>('0');
const exportLooperTime = ref<string>('0');

// 新增：活套最大设定值
const inletLooperMaxSet = ref(0);
const middleLooperMaxSet = ref(0);
const exportLooperMaxSet = ref(0);

// 新增：开卷机剩余长度
const uncoiler_remaining_length_a = ref<number>(0);
const uncoiler_remaining_length_b = ref<number>(0);

// 新增：卷取长度
const coiler_remaining_length_a = ref<number>(0);

// 新增：厚度偏差相关
const homeBatchData = ref<number>(0);
const Targetthickness = ref<number>(0);

// 新增：轧机入口速度
const mill_enter_speed = ref<number>(0);

// 新增：工艺段套量
const techLooperData = ref<number>(0);

// 新增：延伸率
const elongationSet = ref<any>('');
const elongationAct = ref<any>('');
const elongationAlarm = ref<boolean>(false);

// 新增：拉矫机模式
const sub_open = ref<boolean>(false);
const sub_relax = ref<boolean>(false);
const sub_closed = ref<boolean>(false);

// 新增：速度相关
const tcmSpeed = ref<number>(0);
const entSpeed = ref<number>(0);
const extSpeed = ref<number>(0);
const ypjSpeed = ref<number>(0);

// 新增：产量数据
const dailyProduction = ref<number>(0);
const dailyTopProd = ref<number>(0);
const monthProduction = ref<number>(0);
const monthTopProd = ref<number>(0);
const monthSet = ref<number>(0);
const monthRate = ref<number>(0);
const TVData = ref<any>({});
const TVACTData = ref<any>({});

// 新增：产量记录相关
const dayTop = ref<any>({});
const monthTop = ref<any>({});
const lastDayTop = ref<any>({});
const lastMonthTop = ref<any>({});

// 新增：产量图表数据（按照 index old.vue 的方式）
const millUnitX = ref<string[]>([]);
const millUnitTarget = ref<number[]>([]); // 预测产量（吨）- 用于tooltip
const millUnitActual = ref<number[]>([]); // 实际产量（吨）- 用于tooltip
const millUnitAchiRate = ref<number[]>([]); // 达成率（%）
const millUnitTargetRollCounts = ref<number[]>([]); // 预测生产卷数 - 用于柱状图
const millUnitActualRollCounts = ref<number[]>([]); // 实际生产卷数 - 用于柱状图

// 新增：日计划数据（从接口获取）
const dayPlan = ref<number>(0); // 日计划（dayPlan）
const dayPlanXiada = ref<number>(0); // 日计划下达产量（dayPlanXiada）
const dayPlanRate = ref<number>(0); // 日计划达成率（dayPlanRate）
const dayAct = ref<number>(0); // 日实际产量（dayAct）
const dayActRate = ref<number>(0); // 日实际达成率（dayActRate）

// 新增：5个小蓝条数据（位置和数据待调整）
// blueBarData1-3 已改为使用 svgInfo 中的数据（extAISet, craftAISet, entAISet）

// 新增：剩余时长
const rollCoilId = ref<string>('');
const rollCoilData = ref<any>(null);
const rollCoilAllTime = ref<any>('-');
const rollCoilLeftTime = ref<any>('-');
const timeAllWidth = 26;
let firstIn = true;

// 新增：计算属性
const dayText = computed(() => {
  if (dayTop.value.date) {
    return `3#酸轧机组：${dayjs(dayTop.value.date, 'YYYYMMDD').format('YYYY年M月D日')}产量${dayTop.value.output}吨 , 破日产记录 , 原记录(${dayjs(lastDayTop.value.date, 'YYYYMMDD').format('YYYY年M月D日')}产量${lastDayTop.value.output}吨)`;
  }
  return '';
});

const monthText = computed(() => {
  if (monthTop.value.date) {
    return `3#酸轧机组：${dayjs(monthTop.value.date, 'YYYYMM').format('YYYY年M月')}产量${monthTop.value.output}吨 , 破月产记录 , 原记录(${dayjs(lastMonthTop.value.date, 'YYYYMM').format('YYYY年M月')}产量${lastMonthTop.value.output}吨)`;
  }
  return '';
});

const levelerModeText = computed(() => {
  if (svgInfo.levelerAutoMode === 1) {
    return '自动';
  }
  if (svgInfo.levelerManualMode === 1) {
    return '手动';
  }
  return '未启用';
});

// 新增：速度仪表盘配置
const SpeedBaseOption: any = {
  middle_speed1: {
    max: 1200,
    segmentation1: 200,
    segmentation2: 800,
  },
  middle_speed2: {
    max: 700,
    segmentation1: 80,
    segmentation2: 300,
  },
  middle_speed4: {
    max: 300,
    segmentation1: 80,
    segmentation2: 250,
  },
  middle_speed5: {
    max: 300,
    segmentation1: 80,
    segmentation2: 250,
  },
  middle_speed6: {
    max: 300,
    segmentation1: 80,
    segmentation2: 250,
  },
};

// 新增：格式化函数
const numberFormat = (number: any, fixed: number = 0) => {
  fixed = fixed == undefined ? 0 : fixed;
  return number == undefined ? '0' : Number(parseFloat(number).toFixed(fixed));
};

const numberFormat3 = (number: any) => {
  return number == undefined ? '0' : Number(parseFloat(number).toFixed(3));
};

const decoratePieData = (pieData: PieDataItem[], gray: boolean = false) => {
  return [
    pieData.map((item) => {
      let color = '#00c853';
      if (gray) {
        color = '#888';
      } else if (item.realValue === null) {
        color = '#888';
      } else if (item.standard && item.realValue > item.standard) {
        color = '#ff4d4f';
      }
      return {
        ...item,
        itemStyle: { color },
      };
    }),
  ];
};

// 获取开卷机当前步骤信息
function getUncoilerCurrentStep(uncoilerData: Record<string, any>, lastData: Record<string, any> | null, currentStepInfo: CurrentStepInfo | null): CurrentStepInfo {
  const steps = [
    { name: '装卷', startKey: 'porCarStartTimes', endKey: 'porExpandTime', stdKey: 'diffPorExpand' },
    { name: '开卷', startKey: 'porExpandTime', endKey: 'straightTimes', stdKey: 'diffStraight' },
    { name: '穿带', startKey: 'straightTimes', endKey: 'headToCutterTime', stdKey: 'diffHeadToCutter' },
    { name: '剪切', startKey: 'headToCutterTime', endKey: 'arriveWaitPosTime', stdKey: 'diffArriveWait' },
  ];

  const getTime = (key: string): number | null => {
    const timeStr = uncoilerData[key];
    if (!timeStr) return null;
    return new Date(timeStr).getTime();
  };

  const getLastTime = (key: string): number | null => {
    if (!lastData) return null;
    const timeStr = lastData[key];
    if (!timeStr) return null;
    return new Date(timeStr).getTime();
  };

  const currentTime = Date.now();

  // 从前往后查找第一个已开始但未完成的步骤
  for (let i = 0; i < steps.length; i++) {
    const step = steps[i];
    const startTime = getTime(step.startKey);
    const endTime = getTime(step.endKey);
    const lastStartTime = getLastTime(step.startKey);
    const lastEndTime = getLastTime(step.endKey);

    // 判断数据是否没有变化
    const dataUnchanged = lastData &&
      startTime === lastStartTime &&
      endTime === lastEndTime;

    // 检查当前显示的步骤是否就是这个步骤，且倒计时已经到0
    const isCurrentStep = currentStepInfo && currentStepInfo.stepName === step.name;
    const countdownFinished = isCurrentStep && currentStepInfo.countdown <= 0;

    if (startTime !== null && endTime === null) {
      // 如果数据没有变化，且当前步骤的倒计时已经到0，切换到下一个步骤
      if (dataUnchanged && countdownFinished && i < steps.length - 1) {
        // 切换到下一个步骤（即使没有实际数据也要显示）
        const nextStep = steps[i + 1];
        const nextStartTime = getTime(nextStep.startKey);
        const nextEndTime = getTime(nextStep.endKey);
        const std = Number(diffTimeStandard.value?.[nextStep.stdKey]) || 0;

        if (nextStartTime !== null && nextEndTime === null) {
          // 下一个步骤已开始但未完成
          const elapsedTime = Math.floor((currentTime - nextStartTime) / 1000);
          const countdown = Math.max(0, std - elapsedTime);
          return {
            stepName: nextStep.name,
            standardTime: std,
            countdown: countdown,
            startTime: nextStartTime,
            step: 0,
          };
        } else {
          // 下一个步骤还没开始，显示下一个步骤的标准时间并开始倒计时
          return {
            stepName: nextStep.name,
            standardTime: std,
            countdown: std,
            startTime: null, // 即使没有实际数据，也显示并开始倒计时
            step: 0,
          };
        }
      }

      // 找到当前正在进行的步骤
      const std = Number(diffTimeStandard.value?.[step.stdKey]) || 0;
      // 计算已运行时间（秒）
      const elapsedTime = Math.floor((currentTime - startTime) / 1000);
      // 倒计时 = 标准时间 - 已运行时间
      const countdown = Math.max(0, std - elapsedTime);
      return {
        stepName: step.name,
        standardTime: std,
        countdown: countdown,
        startTime: startTime,
        step: 0,
      };
    }
  }

  // 如果所有步骤都完成了，检查是否需要切换到下一个循环的第一个步骤
  const lastStep = steps[steps.length - 1];
  const lastStepEndTime = getTime(lastStep.endKey);
  if (lastStepEndTime !== null) {
    const isLastStep = currentStepInfo && currentStepInfo.stepName === lastStep.name;
    const countdownFinished = isLastStep && currentStepInfo.countdown <= 0;

    // 如果最后一个步骤的倒计时也到0了，切换到第一个步骤
    if (countdownFinished) {
      const firstStep = steps[0];
      const std = Number(diffTimeStandard.value?.[firstStep.stdKey]) || 0;
      return {
        stepName: firstStep.name,
        standardTime: std,
        countdown: std,
        startTime: null,
        step: 0,
      };
    }

    const std = Number(diffTimeStandard.value?.[lastStep.stdKey]) || 0;
    return {
      stepName: lastStep.name,
      standardTime: std,
      countdown: 0,
      startTime: null,
      step: 0,
    };
  }

  // 如果所有步骤都没开始，返回第一个步骤
  const firstStep = steps[0];
  const std = Number(diffTimeStandard.value?.[firstStep.stdKey]) || 0;
  return {
    stepName: firstStep.name,
    standardTime: std,
    countdown: std,
    startTime: null,
    step: 0,
  };
}

function convertUncoilerDataToPie(uncoilerData: Record<string, any>): PieDataItem[] {
  const pieData: PieDataItem[] = [];
  const steps = [
    { name: '剪切', startKey: 'headToCutterTime', endKey: 'arriveWaitPosTime', stdKey: 'diffArriveWait' },
    { name: '穿带', startKey: 'straightTimes', endKey: 'headToCutterTime', stdKey: 'diffHeadToCutter' },
    { name: '开卷', startKey: 'porExpandTime', endKey: 'straightTimes', stdKey: 'diffStraight' },
    { name: '装卷', startKey: 'porCarStartTimes', endKey: 'porExpandTime', stdKey: 'diffPorExpand' },
  ];
  const getTime = (key: string): number | null => {
    const timeStr = uncoilerData[key];
    if (!timeStr) return null;
    return new Date(timeStr).getTime();
  };
  const currentTime = Date.now();
  for (const step of steps) {
    const startTime = getTime(step.startKey);
    const endTime = getTime(step.endKey);
    let diff: number | null = null;
    let displayName = step.name;
    if (startTime !== null && endTime !== null) {
      diff = Math.abs(Math.floor((endTime - startTime) / 1000));
    } else if (startTime !== null && endTime === null) {
      diff = Math.abs(Math.floor((currentTime - startTime) / 1000));
      displayName = `${step.name}运行时间`;
    } else if (startTime === null && endTime !== null) {
      diff = Math.abs(Math.floor((endTime - currentTime) / 1000));
      displayName = `${step.name}运行时间`;
    }
    const std = Number(diffTimeStandard.value?.[step.stdKey]) || null;
    if (std !== null) {
      pieData.push({
        name: displayName,
        value: 1,
        realValue: diff,
        standard: std,
      });
    }
  }
  return pieData;
}

const fetchDiffTimeStandard = async () => {
  try {
    const res = await fetchDataWithRetry(() => acidRollingApi.getDiffTime({}, { signal: controller.signal }));
    if (res?.data?.data && Array.isArray(res.data.data) && res.data.data.length > 0) {
      diffTimeStandard.value = res.data.data[0] || {};
      // 标准值更新后立即刷新一次图表
      fetchSequenceTrackingData();
    }
  } catch (error: any) {
    if (axios.isCancel(error)) {
      console.log('Request canceled: fetchDiffTimeStandard');
      return;
    }
    console.error('获取时间差标准值失败:', error);
  }
};

const fetchSequenceTrackingData = async () => {
  try {
    const res = await fetchDataWithRetry(() => rollingSimulationApi.rest({ name: 'TCM2280_zonetrk' }, { signal: controller.signal }));
    const data = res?.data || {};

    // 获取卷号
    const newPor1CoilNo = data?.por1CoilNo || '';
    const newPor2CoilNo = data?.por2CoilNo || '';
    por1CoilNo.value = newPor1CoilNo;
    por2CoilNo.value = newPor2CoilNo;

    // 步骤名称映射：1-装卷 2-开卷 3-穿卷 4-切头
    const stepNameMap: Record<number, string> = {
      1: '装卷',
      2: '开卷',
      3: '穿卷',
      4: '切头',
    };

    // 获取标准时间（从diffTimeStandard中获取）
    const getStandardTime = (step: number): number => {
      const timeMap: Record<number, string> = {
        1: 'diffLoadedTime',      // 装卷标准时间
        2: 'diffUncoiledTime',    // 开卷标准时间
        3: 'diffThreadingTime',   // 穿卷标准时间
        4: 'diffHeadCuttingTime', // 切头标准时间
      };
      const key = timeMap[step];
      return key ? Number(diffTimeStandard.value?.[key]) || 0 : 0;
    };

    // 获取1#开卷机步骤
    if (por1CoilNo.value) {
      try {
        const stepRes = await axios.get('/eapi/tcmEff/selectStep', {
          params: { entId: por1CoilNo.value },
          signal: controller.signal
        });

        const step = stepRes?.data?.data?.step || 0;

        // 检查步骤是否变化
        if (step !== uncoiler1CurrentStep.value.step) {
          // 步骤变化，重置倒计时
          const standardTime = getStandardTime(step);
          uncoiler1CurrentStep.value = {
            stepName: stepNameMap[step] || '-',
            standardTime: standardTime,
            countdown: standardTime,
            startTime: Date.now(),
            step: step,
          };
        }
      } catch (error) {
        console.error('获取1#开卷机步骤失败:', error);
      }
    } else {
      uncoiler1CurrentStep.value = { stepName: '-', standardTime: 0, countdown: 0, startTime: null, step: 0 };
    }

    // 获取2#开卷机步骤
    if (por2CoilNo.value) {
      try {
        const stepRes = await axios.get('/eapi/tcmEff/selectStep', {
          params: { entId: por2CoilNo.value },
          signal: controller.signal
        });

        const step = stepRes?.data?.data?.step || 0;

        // 检查步骤是否变化
        if (step !== uncoiler2CurrentStep.value.step) {
          // 步骤变化，重置倒计时
          const standardTime = getStandardTime(step);
          uncoiler2CurrentStep.value = {
            stepName: stepNameMap[step] || '-',
            standardTime: standardTime,
            countdown: standardTime,
            startTime: Date.now(),
            step: step,
          };
        }
      } catch (error) {
        console.error('获取2#开卷机步骤失败:', error);
      }
    } else {
      uncoiler2CurrentStep.value = { stepName: '-', standardTime: 0, countdown: 0, startTime: null, step: 0 };
    }

    // 获取效率数据用于饼图显示
    const loadEfficiencyData = async (coilId: string) => {
      const resEff = await fetchDataWithRetry(() => acidRollingApi.getAcidEfficiency({ entid: coilId }, { signal: controller.signal }));
      return resEff?.data?.data || {};
    };

    // 更新焊机数据
    const por = data?.por;
    const newWelderCoilNo = por === '1' ? por1CoilNo.value : (por === '2' ? por2CoilNo.value : '');
    welderCoilNo.value = newWelderCoilNo;

    let welderPie: PieDataItem[] = [];
    let welderGray = false;
    if (welderCoilNo.value) {
      const effData = await loadEfficiencyData(welderCoilNo.value);
      welderPie = convertWelderDataToPie(effData);
    } else {
      welderGray = true;
    }

    // 更新1#开卷机饼图
    let uncoiler1Pie: PieDataItem[] = [];
    let uncoiler1Gray = false;
    if (por1CoilNo.value) {
      const effData1 = await loadEfficiencyData(por1CoilNo.value);
      uncoiler1Pie = convertUncoilerDataToPie(effData1);
    } else {
      uncoiler1Gray = true;
    }

    // 更新2#开卷机饼图
    let uncoiler2Pie: PieDataItem[] = [];
    let uncoiler2Gray = false;
    if (por2CoilNo.value) {
      const effData2 = await loadEfficiencyData(por2CoilNo.value);
      uncoiler2Pie = convertUncoilerDataToPie(effData2);
    } else {
      uncoiler2Gray = true;
    }

    welderPieSeries.value = decoratePieData(welderPie, welderGray);
    uncoiler1PieSeries.value = decoratePieData(uncoiler1Pie, uncoiler1Gray);
    uncoiler2PieSeries.value = decoratePieData(uncoiler2Pie, uncoiler2Gray);
  } catch (error: any) {
    if (axios.isCancel(error)) {
      console.log('Request canceled: fetchSequenceTrackingData');
      return;
    }
    console.error('获取时序跟踪数据失败:', error);
    welderPieSeries.value = [[]];
    uncoiler1PieSeries.value = [[]];
    uncoiler2PieSeries.value = [[]];
  }
};

// 获取焊机当前步骤信息
function getWelderCurrentStep(welderData: Record<string, any>, lastData: Record<string, any> | null, currentStepInfo: CurrentStepInfo | null): CurrentStepInfo {
  const steps = [
    { name: '带头到焊机-带尾到焊机', startKey: 'tailToweldTime', endKey: 'anotherheadToweldTime', stdKey: 'diffHeadToCutter' },
    { name: '焊接完成-焊机激活', startKey: 'activeWeldTimes', endKey: 'finishedWeldTime', stdKey: 'diffArriveWait' },
  ];

  const getTime = (key: string): number | null => {
    const timeStr = welderData[key];
    if (!timeStr) return null;
    return new Date(timeStr).getTime();
  };

  const getLastTime = (key: string): number | null => {
    if (!lastData) return null;
    const timeStr = lastData[key];
    if (!timeStr) return null;
    return new Date(timeStr).getTime();
  };

  const currentTime = Date.now();

  // 从前往后查找第一个已开始但未完成的步骤
  for (let i = 0; i < steps.length; i++) {
    const step = steps[i];
    const startTime = getTime(step.startKey);
    const endTime = getTime(step.endKey);
    const lastStartTime = getLastTime(step.startKey);
    const lastEndTime = getLastTime(step.endKey);

    // 判断数据是否没有变化
    const dataUnchanged = lastData &&
      startTime === lastStartTime &&
      endTime === lastEndTime;

    // 检查当前显示的步骤是否就是这个步骤，且倒计时已经到0
    const isCurrentStep = currentStepInfo && currentStepInfo.stepName === step.name;
    const countdownFinished = isCurrentStep && currentStepInfo.countdown <= 0;

    if (startTime !== null && endTime === null) {
      // 如果数据没有变化，且当前步骤的倒计时已经到0，切换到下一个步骤
      if (dataUnchanged && countdownFinished && i < steps.length - 1) {
        // 切换到下一个步骤（即使没有实际数据也要显示）
        const nextStep = steps[i + 1];
        const nextStartTime = getTime(nextStep.startKey);
        const nextEndTime = getTime(nextStep.endKey);
        const std = Number(diffTimeStandard.value?.[nextStep.stdKey]) || 0;

        if (nextStartTime !== null && nextEndTime === null) {
          // 下一个步骤已开始但未完成
          const elapsedTime = Math.floor((currentTime - nextStartTime) / 1000);
          const countdown = Math.max(0, std - elapsedTime);
          return {
            stepName: nextStep.name,
            standardTime: std,
            countdown: countdown,
            startTime: nextStartTime,
            step: 0,
          };
        } else {
          // 下一个步骤还没开始，显示下一个步骤的标准时间并开始倒计时
          return {
            stepName: nextStep.name,
            standardTime: std,
            countdown: std,
            startTime: null, // 即使没有实际数据，也显示并开始倒计时
            step: 0,
          };
        }
      }

      // 找到当前正在进行的步骤
      const std = Number(diffTimeStandard.value?.[step.stdKey]) || 0;
      // 计算已运行时间（秒）
      const elapsedTime = Math.floor((currentTime - startTime) / 1000);
      // 倒计时 = 标准时间 - 已运行时间
      const countdown = Math.max(0, std - elapsedTime);
      return {
        stepName: step.name,
        standardTime: std,
        countdown: countdown,
        startTime: startTime,
        step: 0,
      };
    }
  }

  // 如果所有步骤都完成了，检查是否需要切换到下一个循环的第一个步骤
  const lastStep = steps[steps.length - 1];
  const lastStepEndTime = getTime(lastStep.endKey);
  if (lastStepEndTime !== null) {
    const isLastStep = currentStepInfo && currentStepInfo.stepName === lastStep.name;
    const countdownFinished = isLastStep && currentStepInfo.countdown <= 0;

    // 如果最后一个步骤的倒计时也到0了，切换到第一个步骤
    if (countdownFinished) {
      const firstStep = steps[0];
      const std = Number(diffTimeStandard.value?.[firstStep.stdKey]) || 0;
      return {
        stepName: firstStep.name,
        standardTime: std,
        countdown: std,
        startTime: null,
        step: 0,
      };
    }

    const std = Number(diffTimeStandard.value?.[lastStep.stdKey]) || 0;
    return {
      stepName: lastStep.name,
      standardTime: std,
      countdown: 0,
      startTime: null,
      step: 0,
    };
  }

  // 如果所有步骤都没开始，返回第一个步骤
  const firstStep = steps[0];
  const std = Number(diffTimeStandard.value?.[firstStep.stdKey]) || 0;
  return {
    stepName: firstStep.name,
    standardTime: std,
    countdown: std,
    startTime: null,
    step: 0,
  };
}

function convertWelderDataToPie(welderData: Record<string, any>): PieDataItem[] {
  const pieData: PieDataItem[] = [];
  const steps = [
    { name: '带头到焊机-带尾到焊机', startKey: 'tailToweldTime', endKey: 'anotherheadToweldTime', stdKey: 'diffHeadToCutter' },
    { name: '焊接完成-焊机激活', startKey: 'activeWeldTimes', endKey: 'finishedWeldTime', stdKey: 'diffArriveWait' },
  ];
  const getTime = (key: string): number | null => {
    const timeStr = welderData[key];
    if (!timeStr) return null;
    return new Date(timeStr).getTime();
  };
  const currentTime = Date.now();
  for (const step of steps) {
    const startTime = getTime(step.startKey);
    const endTime = getTime(step.endKey);
    let diff: number | null = null;
    let displayName = step.name;
    if (startTime !== null && endTime !== null) {
      diff = Math.abs(Math.floor((endTime - startTime) / 1000));
    } else if (startTime !== null && endTime === null) {
      diff = Math.abs(Math.floor((currentTime - startTime) / 1000));
      displayName = `${step.name}运行时间`;
    } else if (startTime === null && endTime !== null) {
      diff = Math.abs(Math.floor((endTime - currentTime) / 1000));
      displayName = `${step.name}运行时间`;
    }
    const std = Number(diffTimeStandard.value?.[step.stdKey]) || null;
    pieData.push({
      name: displayName,
      value: 1,
      realValue: diff,
      standard: std,
    });
  }
  return pieData;
}

/*
 * 钢卷跟踪
 */
async function getZoneTrk() {
  let param = {
    name: 'TCM2280_zonetrk',
  };
  rollingSimulationApi.rest(param).then((res) => {
    let zones = res.data.zoneno;
    coilColorMap.value = SearchForCoidId(zones);
    coilIds.value = coilColorMap.value.coilIds;
    coilIds.value = coilIds.value.filter((item: any) => item != 'ENTIDBOOK');
    // 更新焊机状态（闪烁效果）- 完全按照 NewFulllineTrack.vue 的方式：直接调用
    weldMachineState(`${technologicalName}-welder`, res.data.weld);
    inletLooper.value = res.data['loop'][0];
    middleLooper.value = res.data['loop'][1];
    exportLooper.value = res.data['loop'][2];
    techLooperData.value = res.data['loop'][1]; // 工艺段套量
    let trKey = `${technologicalName}-ZONE_tr${res.data.tr}`;
    let trpathKey = trKey + '_path';
    let porKey = `${technologicalName}-ZONE_por${res.data.por}`;
    let porpathKey = porKey + '_path';
    var arr = Object.keys(zones);

    // 获取当前卷信息（包含目标厚度）- 完全按照 NewFulllineTrack.vue 的方式
    getCoilData(zones);

    /**开卷机和卷取机 */
    if (tr === null || tr !== res.data.tr) {
      tr = res.data.tr;
      refreshSVG(zones[arr.length - 1].ti % 10, trpathKey);
      refreshGraphical(zones[arr.length - 1].ti % 10, trKey);
      // 只有当 tr 为 '1' 或 '2' 时才调用 initialSVG，避免报错
      const trStr = String(res.data.tr);
      if (trStr === '1' || trStr === '2') {
        initialSVG(technologicalName, 'tr', trStr);
      }
    }
    if (por === null || por !== res.data.por) {
      por = res.data.por;
      if (res.data.por === 0) {
        initialSVG(technologicalName, 'por', '1');
        initialSVG(technologicalName, 'por', '2');
      }
    }
    if (ti === null || ti !== zones[0].ti) {
      ti = zones[0].ti;
      refreshSVG(zones[0].ti % 10, porpathKey);
      refreshGraphical(zones[0].ti % 10, porKey);
      // 只有当 por 为 '1' 或 '2' 时才调用 initialSVG，避免报错
      // 注意：如果 por === 0，已经在上面处理过了，这里不需要再调用
      const porStr = String(res.data.por);
      if (porStr === '1' || porStr === '2') {
        initialSVG(technologicalName, 'por', porStr);
      }
    }
    for (let i in zones) {
      let pathkey = `${technologicalName}-ZONE${i}`;
      refreshSVG(zones[i].ti % 10, pathkey);
    }
    // 新增：同步生成进度条区段
    const zonesArr = Object.values(zones);
    coilIdCountMap.value = new Map<string, number>();
    [...zonesArr].reverse().forEach((item: any) => {
      const coilId = item.entId;
      if (coilId !== undefined && coilId !== null) {
        if (coilIdCountMap.value.has(coilId)) {
          coilIdCountMap.value.set(coilId, coilIdCountMap.value.get(coilId)! + 1);
        } else {
          coilIdCountMap.value.set(coilId, 1);
        }
      }
    });

    // 获取当前卷ID并更新剩余时长
    // NewFulllineTrack.vue: let nowRollCoilId = zones[29].entId;
    let nowRollCoilId = zones[29]?.entId;
    if (nowRollCoilId && nowRollCoilId !== rollCoilId.value) {
      rollCoilId.value = nowRollCoilId;
      getRollCoilData(nowRollCoilId);
    }

    // 获取PDI数据
    if (coilIds.value && coilIds.value.length > 0) {
      getPidMesInfo();
    }

    // 处理轧机颜色变化（完全按照 NewFulllineTrack.vue 的方式：直接调用 segmentStop）
    // NewFulllineTrack.vue 中：segmentStop(res.speed); 是直接调用的
    if (res.data && res.data.speed && Array.isArray(res.data.speed) && res.data.speed.length >= 6) {
      segmentStop(res.data.speed);
    }
  });
}

// 处理各段停止状态，更新SVG颜色（完全按照 NewFulllineTrack.vue 的方式）
const segmentStop = (speeds: any[]) => {
  if (!speeds || !Array.isArray(speeds) || speeds.length < 6) {
    return;
  }

  const entState = speeds[0] * 1 == 0;
  const tchState = speeds[2] * 1 == 0;
  const cirState = speeds[4] * 1 == 0;
  const rollState = speeds[5] * 1 == 0;

  // 只在状态改变时才更新（与 NewFulllineTrack.vue 保持一致）
  if (entStop.value != entState) {
    entStop.value = entState;
    rollStateFun(entState, 1, 34);
  }
  if (tchStop.value != tchState) {
    tchStop.value = tchState;
    rollStateFun(tchState, 35, 52);
  }
  if (cirStop.value != cirState) {
    cirStop.value = cirState;
    rollStateFun(cirState, 53, 68);
  }
  if (rollStop.value != rollState) {
    rollStop.value = rollState;
    rollStateFun(rollState, 69, 79);
  }
};




const getSteelInfo = async () => {
  await rollingSimulationApi
    .getSteelInfo(coilIds.value, { signal: controller.signal })
    .then((res) => {
      // 添加空值检查，防止 forEach 报错
      if (res?.data?.data && Array.isArray(res.data.data)) {
        res.data.data.forEach((item: any) => {
          if (coilIds.value[0] && item.entid === coilIds.value[0]) {
            coilInfo.value[0] = item;
          }
          if (coilIds.value[1] && item.entid === coilIds.value[1]) {
            coilInfo.value[1] = item;
          }
          if (coilIds.value[2] && item.entid === coilIds.value[2]) {
            coilInfo.value[2] = item;
          }
        });
      }
      // 从右向左
      coilInfo.value = coilInfo.value.reverse();
    })
    .catch((err) => {
      if (axios.isCancel(err)) {
        console.log('getSteelInfo canceled');
      } else {
        // Handle other errors if needed
        console.error('getSteelInfo error', err);
      }
    });
}; // 获取AI设定值接口

async function fetchAISetValues() {
  const param = {
    action: 'get_tags',
    operator: 'abc',
    terminal: 'FM_01',
    body: [
      // 速度设定与AI模式相关标签
      { tagName: 'tcm_enSpeedAImodel', timestamp: 0 },
      { tagName: 'tcm_processSpeedAImodel', timestamp: 0 },
      { tagName: 'tcm_millSpeedAImodel', timestamp: 0 },
      { tagName: 'PLTCM_DIR.EntSpeed', timestamp: 0 },
      { tagName: 'PLTCM_DIR.ProcessSpeed', timestamp: 0 },
      { tagName: 'PLTCM_DIR.TandemSpeed', timestamp: 0 },
      { tagName: 'tcm_por1_len', timestamp: 0 },
      { tagName: 'tcm_por2_len', timestamp: 0 },
    ],
  };
  try {
    const res = await rollingSimulationApi.HMI(param, { signal: controller.signal });
    if (res && res.data) {
      // 将结果按 tagName 建立索引，避免依赖顺序
      const results = Array.isArray(res.data.results) ? res.data.results : [];
      const resultMap = new Map<string, any>();
      results.forEach((r: any) => {
        if (r && r.tagName !== undefined) {
          resultMap.set(String(r.tagName), r.value);
        }
      });

      // 三个AI模式赋值并打印
      svgInfo.entAISetFlag =
        resultMap.get('tcm_enSpeedAImodel') === 0 || resultMap.get('tcm_enSpeedAImodel') === 1 ? Number(resultMap.get('tcm_enSpeedAImodel')) : null;
      svgInfo.craftAISetFlag =
        resultMap.get('tcm_processSpeedAImodel') === 0 || resultMap.get('tcm_processSpeedAImodel') === 1
          ? Number(resultMap.get('tcm_processSpeedAImodel'))
          : null;
      svgInfo.extAISetFlag =
        resultMap.get('tcm_millSpeedAImodel') === 0 || resultMap.get('tcm_millSpeedAImodel') === 1
          ? Number(resultMap.get('tcm_millSpeedAImodel'))
          : null;

      // 原有速度/剩余长度取值（向后兼容）
      svgInfo.entAISet = Math.round(Number(resultMap.get('PLTCM_DIR.EntSpeed')) || 0);
      svgInfo.craftAISet = Math.round(Number(resultMap.get('PLTCM_DIR.ProcessSpeed')) || 0);
      svgInfo.extAISet = Math.round(Number(resultMap.get('PLTCM_DIR.TandemSpeed')) || 0);
      svgInfo.trLength1 = Math.round(Number(resultMap.get('tcm_por1_len')) || 0);
      svgInfo.trLength2 = Math.round(Number(resultMap.get('tcm_por2_len')) || 0);
    }
  } catch (e: any) {
    if (axios.isCancel(e)) {
      console.log('Request canceled: fetchAISetValues');
      return;
    }
    console.error('AI设定值接口调用失败', e);
  }
}

async function fetchGaugeData() {
  try {
    const { data: res } = await fetchDataWithRetry(() =>
      axios.get('http://10.171.7.100:8090/restapi?name=TCM2280_itemtag', { signal: controller.signal })
    );
    // 获取活套数据
    const { data: realData } = await fetchDataWithRetry(() =>
      axios.get('http://10.171.7.100:8090/restapi?name=TCM2280_RealData', { signal: controller.signal })
    );

    // 获取速度数据（所有速度数据都取整）
    entSpeed.value = Math.round(Number(res['M_010_011DS_ANS']) || 0);
    extSpeed.value = Math.round(Number(res['M_400_262NI']) || 0);
    tcmSpeed.value = Math.round(Number(res['M_010_103NI']) || 0);
    ypjSpeed.value = Math.round(Number(res['M_010_105NI']) || 0);
    svgInfo.entRollingMillSpeed = Math.round(Number(res['L_AGC_STRIPSFB0']) || 0);
    mill_enter_speed.value = Math.round(Number(res['M_010_014DS_ANS']) || 0);

    const inletLooperValue = Number(realData['L_ELPR_PosFbk_1']) || 0;
    const middleLooperValue = Number(realData['L_ILPR_PosFbk_1']) || 0;
    const exportLooperValue = Number(realData['L_XLPR_PosFbk_1']) || 0;
    svgInfo.entSpeed = entSpeed.value;
    svgInfo.craftSpeed = tcmSpeed.value;

    // 更新活套套量柱形图（更新3D钻石顶部样式的两个series）
    looperData.value = [Math.round(exportLooperValue), Math.round(middleLooperValue), Math.round(inletLooperValue)];

    const bar1 = echarts.getInstanceByDom(document.getElementById('bar1') as HTMLElement);
    if (bar1) {
      bar1.setOption({
        series: [
          {
            data: looperData.value, // 钻石顶部
          },
          {
            data: looperData.value, // 柱体
          },
        ],
      });
    }

    // 获取最大设定值，保留整数
    inletLooperMaxSet.value = Math.round(Number(realData['M_101_214DS_ANS']) || 0);
    middleLooperMaxSet.value = Math.round(Number(realData['M_300_110DS_ANS']) || 0);
    exportLooperMaxSet.value = Math.round(Number(realData['M_300_113DS_ANS']) || 0);

    // 计算活套时间
    inletLooperTime.value = sleeveDeclineTime(technologicalName, 'entrance', entSpeed.value, tcmSpeed.value, inletLooper.value / 100);
    exportLooperTime.value = sleeveDeclineTime(technologicalName, 'exit', tcmSpeed.value, extSpeed.value, exportLooper.value / 100);

    // 更新开卷机剩余长度
    uncoiler_remaining_length_a.value = res['M_101_137NI'] || 0;
    uncoiler_remaining_length_b.value = res['M_101_147NI'] || 0;

    // 更新卷取长度
    coiler_remaining_length_a.value = res['L_TNR2_LENFB'] || 0;

    // 更新厚度偏差
    homeBatchData.value = Number(parseFloat(res['M_400_208NI_EXIT'] || '0').toFixed(3));

    // 更新延伸率
    elongationAct.value = res['M_201_142NI'] || '';
    elongationSet.value = res['M_201_141NI'] || '';
    if (elongationAct.value != 0 && Math.abs(elongationSet.value - elongationAct.value) / elongationAct.value >= 0.3) {
      elongationAlarm.value = true;
    } else {
      elongationAlarm.value = false;
    }

    // 拉矫机模式 OPEN RELAX CLOSED
    sub_open.value = res['M_201_100SL1'] == 1;
    sub_relax.value = res['M_201_100SL2'] == 1;
    sub_closed.value = res['M_201_100SL3'] == 1;

    // 更新横切剪实际切头米数
    svgInfo.crossCuttingShears1Actual = Number(parseFloat(res['L_TRK_POR1_HeadScrap'] || '0').toFixed(2));
    svgInfo.crossCuttingShears2Actual = Number(parseFloat(res['L_TRK_POR2_HeadScrap'] || '0').toFixed(2));

    // 更新1#矫直机压下量
    svgInfo.straightener1EntSet = Number(parseFloat(res['M_113_113NI'] || '0').toFixed(2));
    svgInfo.straightener1EntFbk = Number(parseFloat(res['M_113_110NI'] || '0').toFixed(2));
    svgInfo.straightener1ExtSet = Number(parseFloat(res['M_113_123NI'] || '0').toFixed(2));
    svgInfo.straightener1ExtFbk = Number(parseFloat(res['M_113_120NI'] || '0').toFixed(2));

    // 更新2#矫直机压下量
    svgInfo.straightener2EntSet = Number(parseFloat(res['M_114_113NI'] || '0').toFixed(2));
    svgInfo.straightener2EntFbk = Number(parseFloat(res['M_114_110NI'] || '0').toFixed(2));
    svgInfo.straightener2ExtSet = Number(parseFloat(res['M_114_123NI'] || '0').toFixed(2));
    svgInfo.straightener2ExtFbk = Number(parseFloat(res['M_114_120NI'] || '0').toFixed(2));

    // 更新拉矫机模式
    svgInfo.levelerAutoMode = Number(res['M_237_141PL_SL1'] || 0);
    svgInfo.levelerManualMode = Number(res['M_237_141PL_SL2'] || 0);

    // 更新烘干箱温度实际值
    svgInfo.dryerTemp = Number(parseFloat(res['M_206_111NI'] || '0').toFixed(2));

    // 更新酸槽液位数据（按照 NewFulllineTrack.vue 的方式）
    // 液位字段：M_202_144BR(1#), M_203_128BR(2#), M_204_131BR(3#)
    acidLevels.value = [
      Number(parseFloat(res['M_202_144BR'] || '0').toFixed(0)), // 1#酸槽液位
      Number(parseFloat(res['M_203_128BR'] || '0').toFixed(0)), // 2#酸槽液位
      Number(parseFloat(res['M_204_131BR'] || '0').toFixed(0))  // 3#酸槽液位
    ];

    // 更新酸槽温度数据
    // 温度字段：M_211_259NI(1#), M_211_249NI(2#), M_211_239NI(3#)
    acidTemps.value = [
      Number(parseFloat(res['M_211_259NI'] || '0').toFixed(0)), // 1#酸槽温度
      Number(parseFloat(res['M_211_249NI'] || '0').toFixed(0)), // 2#酸槽温度
      Number(parseFloat(res['M_211_239NI'] || '0').toFixed(0))  // 3#酸槽温度
    ];

    // 更新酸位柱状图ECharts（如果未初始化则初始化）
    nextTick(() => {
      if (acidBarsChartInstance === null) {
        initAcidBarsChart();
      } else {
        updateAcidBarsChart();
      }
    });

    // 更新速度仪表盘（middle_speed6 已改为白色字体显示，不需要仪表盘）
    initScoreChart('middle_speed1', extSpeed.value);
    initScoreChart('middle_speed2', entSpeed.value);
    initScoreChart('middle_speed4', tcmSpeed.value);
    initScoreChart('middle_speed5', ypjSpeed.value);
    // initScoreChart('middle_speed6', mill_enter_speed.value);

    // 左侧柱状图：按实时数据（功率/扭矩/FGC/AGC）构建，与示例组件一致
    try {
      const racks = [
        { 
          name: '1#机架', 
          data1: Number(parseFloat(res['M_400_512NI'] || '0').toFixed(2)), 
          data2: Number(parseFloat(res['M_506_104NI'] || '0').toFixed(2)),
          dataFGC: Number(parseFloat(res['M_406_302NI'] || '0').toFixed(2)),
          dataAGC: Number(parseFloat(res['M_505_148NI'] || '0').toFixed(2))
        },
        { 
          name: '2#机架', 
          data1: Number(parseFloat(res['M_400_514NI'] || '0').toFixed(2)), 
          data2: Number(parseFloat(res['M_506_114NI'] || '0').toFixed(2)),
          dataFGC: Number(parseFloat(res['M_406_332NI'] || '0').toFixed(2)),
          dataAGC: Number(parseFloat(res['M_505_149NI'] || '0').toFixed(2))
        },
        { 
          name: '3#机架', 
          data1: Number(parseFloat(res['M_400_516NI'] || '0').toFixed(2)), 
          data2: Number(parseFloat(res['M_506_124NI'] || '0').toFixed(2)),
          dataFGC: Number(parseFloat(res['M_406_362NI'] || '0').toFixed(2)),
          dataAGC: Number(parseFloat(res['M_505_150NI'] || '0').toFixed(2))
        },
        { 
          name: '4#机架', 
          data1: Number(parseFloat(res['M_400_518NI'] || '0').toFixed(2)), 
          data2: Number(parseFloat(res['M_506_134NI'] || '0').toFixed(2)),
          dataFGC: Number(parseFloat(res['M_406_392NI'] || '0').toFixed(2)),
          dataAGC: Number(parseFloat(res['M_505_151NI'] || '0').toFixed(2))
        },
        { 
          name: '5#机架', 
          data1: Number(parseFloat(res['M_400_520NI'] || '0').toFixed(2)), 
          data2: Number(parseFloat(res['M_506_144NI'] || '0').toFixed(2)),
          dataFGC: Number(parseFloat(res['M_406_422NI'] || '0').toFixed(2)),
          dataAGC: Number(parseFloat(res['M_505_152NI'] || '0').toFixed(2))
        },
      ].reverse();
      // 确保始终是数组格式
      realTimeData.stand = racks.map((it) => it.name) || [];
      realTimeData.data1 = racks.map((it) => it.data1) || [];
      realTimeData.data2 = racks.map((it) => it.data2) || [];
      realTimeData.dataFGC = racks.map((it) => it.dataFGC) || [];
      realTimeData.dataAGC = racks.map((it) => it.dataAGC) || [];
      // updateProductionEfficiencyChart();
    } catch (e) {
      // 如果出错，确保数据是有效的空数组
      console.warn('实时数据更新失败，使用默认值:', e);
      realTimeData.stand = realTimeData.stand || ['1#', '2#', '3#', '4#', '5#'];
      realTimeData.data1 = realTimeData.data1 || [0, 0, 0, 0, 0];
      realTimeData.data2 = realTimeData.data2 || [0, 0, 0, 0, 0];
      realTimeData.dataFGC = realTimeData.dataFGC || [0, 0, 0, 0, 0];
      realTimeData.dataAGC = realTimeData.dataAGC || [0, 0, 0, 0, 0];
    }
  } catch (e: any) {
    if (axios.isCancel(e)) {
      console.log('Request canceled: fetchGaugeData');
      return;
    }
    console.error('获取仪表盘数据失败:', e);
  }
}

// 初始化活套套量柱状图（使用3D钻石顶部样式）
const initLooperBarChart = () => {
  const bar1Dom = document.getElementById('bar1') as HTMLElement;
  if (!bar1Dom) return;

  let bar1Chart = echarts.getInstanceByDom(bar1Dom);
  if (bar1Chart === undefined) {
    bar1Chart = echarts.init(bar1Dom);
  }

  const barWidth = 20;
  const barOption = {
    backgroundColor: 'rgba(0,0,0,0)',
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(0,24,48,0.95)',
      borderColor: '#00f6ff',
      borderWidth: 2,
      textStyle: {
        color: '#fff',
        fontSize: 14
      },
      axisPointer: {
        type: 'shadow',
      },
    },
    legend: {
      data: [
        {
          name: '活套套量',
          icon: 'roundRect',
        }
      ],
      selectedMode: false,
      x: 'center',
      bottom: '2%',
      itemWidth: 16,
      itemHeight: 10,
      itemGap: 20,
      textStyle: {
        color: '#b2eaff',
        fontSize: 12,
      },
    },
    grid: {
      left: '8%',
      top: '15%',
      right: '8%',
      bottom: '12%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: ['3#', '2#', '1#'],
      axisLine: {
        show: true,
        lineStyle: {
          color: 'rgba(78,207,255,0.6)',
        },
      },
      axisLabel: {
        color: '#b2eaff',
        fontSize: 14,
        fontWeight: 'bold',
      },
      axisTick: {
        alignWithLabel: true,
        lineStyle: {
          color: '#0C4F81',
          type: 'solid',
        },
      },
    },
    yAxis: {
      type: 'value',
      name: '套量(%)',
      nameTextStyle: {
        color: '#4F88BD',
        padding: [0, 25, -5, 0],
        fontSize: 12,
      },
      min: 0,
      max: 100,
      axisLine: {
        show: true,
        lineStyle: {
          color: 'rgba(78,207,255,0.6)',
        },
      },
      axisLabel: {
        color: '#4F88BD',
        fontSize: 12,
        formatter: '{value}',
      },
      splitLine: {
        lineStyle: {
          type: 'dotted',
          color: 'rgba(78,207,255,0.15)',
        },
      },
      axisTick: {
        show: false,
      },
    },
    series: [
      {
        z: 2,
        name: '活套套量',
        type: 'pictorialBar',
        symbolPosition: 'end',
        data: [0, 0, 0],
        symbol: 'diamond',
        symbolOffset: [0, '-50%'],
        symbolSize: [barWidth, 10],
        itemStyle: {
          color: function (params: any) {
            const v = params.value;
            if (v < 20 || v > 90) {
              return {
                type: 'linear',
                x: 0,
                x2: 1,
                y: 0,
                y2: 0,
                colorStops: [
                  { offset: 0, color: 'rgba(255, 77, 79, 1)' },
                  { offset: 1, color: 'rgba(255, 150, 150, 1)' },
                ],
              };
            }
            return {
              type: 'linear',
              x: 0,
              x2: 1,
              y: 0,
              y2: 0,
              colorStops: [
                { offset: 0, color: 'rgba(129, 202, 254, 1)' },
                { offset: 1, color: 'rgba(59, 170, 250, 1)' },
              ],
            };
          },
        },
        tooltip: {
          show: false,
        },
      },
      {
        z: 1,
        type: 'bar',
        name: '活套套量',
        barWidth: barWidth,
        data: [0, 0, 0],
        label: {
          show: true,
          position: 'top',
          color: '#fff',
          fontWeight: 'bold',
          fontSize: 14,
          formatter: function (params: any) {
            return params.value + '%';
          },
        },
        itemStyle: {
          color: function (params: any) {
            const v = params.value;
            if (v < 20 || v > 90) {
              return {
                type: 'linear',
                x: 0,
                x2: 1,
                y: 0,
                y2: 0,
                colorStops: [
                  { offset: 0, color: 'rgba(255, 77, 79, 1)' },
                  { offset: 0.5, color: 'rgba(255, 120, 120, 1)' },
                  { offset: 0.5, color: 'rgba(200, 50, 50, 1)' },
                  { offset: 1, color: 'rgba(255, 77, 79, 1)' },
                ],
              };
            }
            return {
              type: 'linear',
              x: 0,
              x2: 1,
              y: 0,
              y2: 0,
              colorStops: [
                { offset: 0, color: 'rgba(20, 67, 133, 1)' },
                { offset: 0.5, color: 'rgba(59, 170, 250, 1)' },
                { offset: 0.5, color: 'rgba(16, 79, 149, 1)' },
                { offset: 1, color: 'rgba(23, 98, 182, 1)' },
              ],
            };
          },
        },
      },
    ],
  };

  bar1Chart.setOption(barOption);
};

// 初始化酸位柱状图（使用ECharts，显示在SVG上方）
let acidBarsChartInstance: any = null;
const initAcidBarsChart = () => {
  const chartDom = document.getElementById('acidBarsChart') as HTMLElement;
  if (!chartDom) {
    console.error('酸位柱状图容器不存在: acidBarsChart');
    return;
  }

  console.log('初始化酸位柱状图, 数据:', acidLevels.value, '温度:', acidTemps.value);

  if (acidBarsChartInstance === null) {
    acidBarsChartInstance = echarts.init(chartDom);
    console.log('创建新的ECharts实例');
  }

  const barWidth = 15;
  const option = {
    backgroundColor: 'rgba(0,0,0,0)',
    tooltip: {
      show: true,
      trigger: 'item',
      triggerOn: 'mousemove',  // 鼠标移动时触发
      backgroundColor: 'rgba(0, 0, 0, 0.95)',
      borderColor: 'rgba(255, 184, 112, 0.8)',
      borderWidth: 2,
      textStyle: {
        color: '#fff',
        fontSize: 13,
        fontWeight: 'bold'
      },
      extraCssText: 'z-index: 99999 !important; pointer-events: auto !important;',
      confine: false,
      enterable: true,  // 允许鼠标进入tooltip
      formatter: (params: any) => {
        console.log('Tooltip 触发:', params);  // 调试信息
        if (!params || params.value === undefined) return '';
        const tankNum = params.dataIndex + 1;
        const levelValue = params.value;
        return `<div style="padding: 8px 12px;">
                    <div style="color: #fff; font-size: 13px; font-weight: bold;">${tankNum}#酸槽液位：<span style="color: #ffb870; font-size: 15px;">${levelValue}</span></div>
                  </div>`;
      },
    },
    grid: {
      left: '8%',
      top: '5%',
      right: '8%',
      bottom: '25%',
      containLabel: false,
    },
    xAxis: {
      type: 'category',
      data: ['1#', '2#', '3#'],
      axisLine: { show: false },
      axisTick: { show: false },
      axisLabel: { show: false },
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: 100,
      show: false,
    },
    series: [
      {
        type: 'bar',
        barWidth: barWidth,
        data: acidLevels.value,
        emphasis: {
          // 悬浬时的高亮效果
          focus: 'self',
          itemStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 1,
              x2: 0,
              y2: 0,
              colorStops: [
                { offset: 0, color: '#ff6b1a' },  // 更亮的橙色
                { offset: 1, color: '#ffd700' }   // 金色
              ]
            },
            borderRadius: [4, 4, 0, 0],
            shadowColor: 'rgba(255, 184, 112, 0.8)',
            shadowBlur: 15,
            borderColor: '#ffd700',
            borderWidth: 2,
          },
        },
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 1,
            x2: 0,
            y2: 0,
            colorStops: [
              { offset: 0, color: '#ff8c42' },
              { offset: 1, color: '#ffb870' }
            ]
          },
          borderRadius: [4, 4, 0, 0],
          shadowColor: 'rgba(255, 140, 66, 0.5)',
          shadowBlur: 10,
        },
        label: {
          show: true,
          position: 'bottom',
          distance: 8,
          formatter: (params: any) => {
            const temp = acidTemps.value[params.dataIndex] || 0;
            return `{temp|${temp}}`;
          },
          rich: {
            temp: {
              color: '#fff',
              fontSize: 11,
              fontWeight: 'bold',
            }
          }
        },
      }
    ],
  };

  acidBarsChartInstance.setOption(option);
};

// 更新酸位柱状图数据
const updateAcidBarsChart = () => {
  if (acidBarsChartInstance) {
    acidBarsChartInstance.setOption({
      series: [
        {
          data: acidLevels.value,
          label: {
            formatter: (params: any) => {
              const temp = acidTemps.value[params.dataIndex] || 0;
              return `{temp|${temp}}`;
            },
          },
        }
      ],
    });
  }
};

// 速度仪表盘初始化函数
const initScoreChart = (chartId: string, value: number) => {
  const chartDom = document.getElementById(chartId) as HTMLElement;
  if (!chartDom) return;

  let speedChart = echarts.getInstanceByDom(chartDom);
  if (speedChart === undefined) {
    speedChart = echarts.init(chartDom);
  }
  const baseOption = SpeedBaseOption[chartId];
  if (!baseOption) return;

  const option = {
    series: [
      {
        type: 'gauge',
        center: ['50%', '50%'],
        startAngle: 180,
        endAngle: 0,
        max: baseOption.max,
        splitNumber: 6,
        axisLine: {
          roundCap: true,
          lineStyle: {
            width: 7,
            color: [
              [
                1,
                new echarts.graphic.LinearGradient(0, 1, 0.9, 1, [
                  { offset: 0, color: '#0b72c3' },
                  // { offset: 0.2, color: '#D86E6D' },
                  // { offset: 0.5, color: '#F1F3F4' },
                  // { offset: 0.65, color: '#F1F3F4' },
                  // { offset: 0.8, color: '#79ACF6' },
                  { offset: 1, color: '#082357' },
                ]),
              ],
            ],
          },
        },
        pointer: {
          icon: 'path://M2090.36389,615.30999 L2090.36389,615.30999 C2091.48372,615.30999 2092.40383,616.194028 2092.44859,617.312956 L2096.90698,728.755929 C2097.05155,732.369577 2094.2393,735.416212 2090.62566,735.56078 C2090.53845,735.564269 2090.45117,735.566014 2090.36389,735.566014 L2090.36389,735.566014 C2086.74736,735.566014 2083.81557,732.63423 2083.81557,729.017692 C2083.81557,728.930412 2083.81732,728.84314 2083.82081,728.755929 L2088.2792,617.312956 C2088.32396,616.194028 2089.24407,615.30999 2090.36389,615.30999 Z',
          length: '45%',
          width: 5,
          color: 'FFFFFF',
          offsetCenter: [0, '-45%']
        },
        axisTick: {
          distance: -14,
          length: 2,
          lineStyle: {
            color: '#00a0e9',
            width: 2,
          },
        },
        splitLine: {
          show: false
        },
        axisLabel: {
          color: '#FFF',
          fontSize: 14,
          distance: -30,
          rotate: 'tangential',
          formatter: function (value: any) {
            if (value === 0 || value === baseOption.segmentation1 || value === baseOption.segmentation2 || value === baseOption.max) {
              return '';
            }
            return '';
          },
        },
        title: {
          offsetCenter: [0, '70%'],
          fontSize: 12,
          color: '#FFF',
        },
        detail: {
          width: '60%',
          lineHeight: 40,
          height: 40,
          borderRadius: 8,
          offsetCenter: [0, '-15%'],
          valueAnimation: true,
          formatter: function (value: number) {
            return '{value|' + value.toFixed(0) + '}{unit|mpm}';
          },
          rich: {
            value: {
              fontSize: 18,
              fontWeight: 'bolder',
              color: '#ffffff',
            },
            unit: {
              fontSize: 12,
              color: '#acb0bf',
              padding: [-5, 0, -30, -28]
            }
          }

        },
        data: [
          {
            value: value,
          },
        ],
      },
    ],
  };
  speedChart.setOption(option);
};

// 获取小时产量
const getHourSpeed = async () => {
  try {
    const res = await fetchDataWithRetry(() =>
      axios.get(`http://10.171.7.100:8090/restapi?name=${technologicalName}_hour`, { signal: controller.signal })
    );
    TVACTData.value = {
      value: res.data?.hour || 0,
      title: '实际小时吨钢',
    };
  } catch (error: any) {
    console.error('获取小时产量失败:', error);
  }
};

// 获取轧机震动数据并更新轧机颜色（完全按照 NewFulllineTrack.vue 的方式）
const getRollingMillVibration = async () => {
  try {
    const res = await fetchDataWithRetry(() =>
      axios.get('/eapi/mq/rollingMillVibration', { signal: controller.signal })
    );

    // axios 返回结构: { data: { data: { "1#_std": "0", ... } } } 或 { data: { "1号_std": "0", ... } }
    // request.get 返回的是 res.data，所以我们需要提取 res.data.data 或 res.data
    let vibrationData = null;

    if (res && res.data) {
      // 如果 res.data.data 存在，说明是嵌套结构（根据网络请求预览，数据结构是 { data: { 1#_std: "0", ... } }）
      if (res.data.data && typeof res.data.data === 'object') {
        vibrationData = res.data.data;
      }
      // 如果 res.data 直接是数据对象（包含 "1#_std" 或 "1号_std" 的键）
      else if (res.data && typeof res.data === 'object') {
        const keys = Object.keys(res.data);
        const hasVibrationKeys = keys.some(key => /^\d+[#号]_std/.test(key));
        if (hasVibrationKeys) {
          vibrationData = res.data;
        }
      }
    }

    if (vibrationData && typeof vibrationData === 'object') {
      // 如果键名是 "1#_std" 格式，需要转换为 "1号_std" 格式（因为 rollingMillStatusHandel 期望 "1号_std"）
      const convertedData: any = {};
      Object.keys(vibrationData).forEach(key => {
        const convertedKey = key.includes('#') ? key.replace('#', '号') : key;
        convertedData[convertedKey] = vibrationData[key];
      });

      // 等待 SVG 加载完成后再更新颜色
      await nextTick();

      // 添加延迟，确保 SVG 完全渲染（完全按照 NewFulllineTrack.vue 的方式）
      setTimeout(() => {
        rollingMillStatusHandel(convertedData);
      }, 1000); // 增加延迟到 1000ms，确保 SVG 完全加载
    }
  } catch (error: any) {
    if (axios.isCancel(error)) {
      console.log('Request canceled: getRollingMillVibration');
      return;
    }
    console.error('获取轧机震动数据失败:', error);
  }
};

// 获取产量图表数据（按照 index old.vue 的方式）
const fetchMillUnitBarData = async () => {
  const param = { dateType: radio.value } as any;
  try {
    const res = await outputAnalysisApi.getTCMMillUnitData(param);
    const list = Array.isArray(res?.data?.data) ? res.data.data : [];

    const x: string[] = [];
    const target: number[] = [];
    const actual: number[] = [];
    const rate: number[] = [];
    const targetCounts: number[] = [];
    const actualCounts: number[] = [];

    for (const e of list) {
      const dateStr = String(e.prodDate ?? e.category ?? '');
      // 格式化日期显示（如果是日期格式，转换为 MM/DD）
      let displayDate = dateStr;
      if (dateStr.includes('-')) {
        const dateParts = dateStr.split('-');
        if (dateParts.length >= 2) {
          displayDate = `${dateParts[1]}/${dateParts[2] || dateParts[0]}`;
        }
      } else if (dateStr.includes('/')) {
        // 如果已经是 MM/DD 格式，直接使用
        displayDate = dateStr;
      }
      x.push(displayDate);
      // 产量（吨）- 用于tooltip显示
      target.push(parseFloat((e.target ?? 0).toFixed ? (e.target as number).toFixed(2) : Number(e.target || 0).toFixed(2)));
      actual.push(parseFloat((e.actual ?? 0).toFixed ? (e.actual as number).toFixed(2) : Number(e.actual || 0).toFixed(2)));
      // 达成率（%）
      rate.push(parseFloat(((e.achi ?? 0) * 100).toFixed(2)));
      // 生产卷数 - 用于柱状图显示
      targetCounts.push(Number(e.targetRoll ?? 0));
      actualCounts.push(Number(e.actualRoll ?? 0));
    }

    millUnitX.value = x;
    millUnitTarget.value = target; // 预测产量（吨）- 用于tooltip
    millUnitActual.value = actual; // 实际产量（吨）- 用于tooltip
    millUnitAchiRate.value = rate; // 达成率（%）
    millUnitTargetRollCounts.value = targetCounts; // 预测生产卷数 - 用于柱状图
    millUnitActualRollCounts.value = actualCounts; // 实际生产卷数 - 用于柱状图

    // 更新产量图表
    updateProductionChart();
  } catch (err) {
    console.error('获取产量图表数据失败:', err);
    millUnitX.value = [];
    millUnitTarget.value = [];
    millUnitActual.value = [];
    millUnitAchiRate.value = [];
    millUnitTargetRollCounts.value = [];
    millUnitActualRollCounts.value = [];
  }
};

// 初始化产量图表（按照 index old.vue 的方式）
const initProductionChart = () => {
  if (!productionChartRef.value) return;
  if (!productionChartInstance) {
    productionChartInstance = echarts.init(productionChartRef.value);
  }
  updateProductionChart();
};

// 更新产量图表（优化样式，更美观）
const updateProductionChart = () => {
  if (!productionChartInstance) return;

  const option = {
    backgroundColor: 'transparent',
    title: { text: '', left: 'center' },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      },
      backgroundColor: 'rgba(0, 24, 48, 0.95)',
      borderColor: '#00f6ff',
      borderWidth: 1,
      textStyle: {
        color: '#fff',
        fontSize: 12
      },
      padding: [8, 12],
      appendToBody: true,
      position: function (point: any) {
        return [point[0], point[1] + 20];
      },
      formatter: function (params: any) {
        if (!Array.isArray(params) || params.length === 0) return '';
        const dataIndex = params[0]?.dataIndex ?? 0;
        const categoryName = params[0]?.name ?? '';
        const byName: Record<string, any> = {} as any;
        for (const it of params) byName[it.seriesName] = it;
        const rows: { label: string; value: string }[] = [];
        const dot = (c: string) =>
          '<span style="display:inline-block;width:10px;height:10px;background-color:' + c + ';border-radius:50%;margin-right:8px;vertical-align:middle;"></span>';
        const formatPercent = (val: number) => {
          const p = val <= 1 ? val * 100 : val;
          const n = Number(p);
          if (!Number.isFinite(n)) return '-%';
          const s = n.toFixed(2).replace(/\.00$/, '');
          return s + '%';
        };
        const targetColor = byName['预测产量']?.color || '#ff9c39';
        const actualColor = byName['实际产量']?.color || '#029cc7';
        const rateColor = byName['达成率']?.color || '#91cc75';
        const targetProd = millUnitTarget.value?.[dataIndex];
        const actualProd = millUnitActual.value?.[dataIndex];
        const targetRoll = millUnitTargetRollCounts.value?.[dataIndex];
        const actualRoll = millUnitActualRollCounts.value?.[dataIndex];
        if (targetProd !== undefined) rows.push({ label: `${dot(targetColor)}预测产量`, value: String(targetProd) + ' 吨' });
        if (actualProd !== undefined) rows.push({ label: `${dot(actualColor)}实际产量`, value: String(actualProd) + ' 吨' });
        if (targetRoll !== undefined) rows.push({ label: `${dot(targetColor)}预测生产卷数`, value: String(targetRoll) + ' 卷' });
        if (actualRoll !== undefined) rows.push({ label: `${dot(actualColor)}实际生产卷数`, value: String(actualRoll) + ' 卷' });
        if (byName['达成率']) rows.push({ label: `${dot(rateColor)}达成率`, value: formatPercent(Number(byName['达成率'].value)) });
        const table =
          '<table style="border-collapse:collapse;width:100%;">' +
          rows
            .map(
              (r) =>
                `<tr style="line-height:24px;"><td style="padding:2px 8px 2px 0;white-space:nowrap;color:#b2eaff;">${r.label}</td><td style="text-align:right;white-space:nowrap;color:#fff;font-weight:600;">${r.value}</td></tr>`
            )
            .join('') +
          '</table>';
        return (categoryName ? `<div style="margin-bottom:6px;font-weight:600;color:#00f6ff;border-bottom:1px solid rgba(0,246,255,0.3);padding-bottom:4px;">${categoryName}</div>` : '') + table;
      },
    },
    grid: {
      left: 50,
      right: 50,
      top: 35,
      bottom: 35,
      containLabel: false
    },
    legend: {
      data: [
        {
          name: '预测产量',
          icon: 'roundRect',
          itemStyle: {
            color: {
              type: 'linear',
              x: 0,
              x2: 1,
              y: 0,
              y2: 0,
              colorStops: [
                { offset: 0, color: 'rgba(20, 67, 133, 1)' },
                { offset: 1, color: 'rgba(23, 98, 182, 1)' },
              ],
            },
          },
        },
        {
          name: '实际产量',
          icon: 'roundRect',
          itemStyle: {
            color: {
              type: 'linear',
              x: 0,
              x2: 1,
              y: 0,
              y2: 0,
              colorStops: [
                { offset: 0, color: 'rgba(28, 121, 153, 1)' },
                { offset: 1, color: 'rgba(18, 91, 111, 1)' },
              ],
            },
          },
        },
        '达成率',
      ],
      selectedMode: false,
      top: 5,
      left: 'center',
      textStyle: {
        color: '#FFFFFF',
        fontSize: 12,
      },
      itemWidth: 16,
      itemHeight: 10,
      itemGap: 50,
    },
    xAxis: {
      type: 'category',
      boundaryGap: true,
      data: millUnitX.value,
      axisLine: {
        lineStyle: {
          color: 'rgba(78,207,255,0.6)',
          width: 2
        }
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        color: '#b2eaff',
        fontSize: 11,
        fontWeight: 'bold',
        margin: 10,
        textShadow: '0 0 6px rgba(0,246,255,0.6)'
      },
    },
    yAxis: [
      {
        type: 'value',
        name: '产量(吨)',
        nameTextStyle: {
          color: '#b2eaff',
          fontSize: 12,
          fontWeight: 'bold',
          padding: [0, 0, 0, 0]
        },
        position: 'left',
        axisLine: {
          show: true,
          lineStyle: {
            color: 'rgba(78,207,255,0.6)',
            width: 2
          }
        },
        axisTick: {
          show: false,
        },
        axisLabel: {
          color: '#b2eaff',
          fontSize: 11,
          formatter: '{value}',
          textShadow: '0 0 6px rgba(0,246,255,0.6)'
        },
        splitLine: {
          show: true,
          lineStyle: {
            color: 'rgba(78,207,255,0.15)',
            type: 'dashed',
            width: 1
          }
        },
      },
      {
        type: 'value',
        name: '达成率(%)',
        nameTextStyle: {
          color: '#91cc75',
          fontSize: 12,
          fontWeight: 'bold',
          padding: [0, 0, 0, 0]
        },
        position: 'right',
        axisLine: {
          show: true,
          lineStyle: {
            color: 'rgba(145,204,117,0.6)',
            width: 2
          }
        },
        axisTick: {
          show: false,
        },
        axisLabel: {
          color: '#91cc75',
          fontSize: 11,
          formatter: '{value}%',
          textShadow: '0 0 6px rgba(145,204,117,0.6)'
        },
        splitLine: {
          show: false
        },
      },
    ],
    series: [
      // 预测产量 - 钻石顶部
      {
        z: 2,
        name: '预测产量',
        type: 'pictorialBar',
        symbolPosition: 'end',
        data: millUnitTarget.value,
        symbol: 'diamond',
        symbolOffset: ['-70%', '-40%'],
        symbolSize: [15, 13],
        yAxisIndex: 0,
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            x2: 1,
            y: 0,
            y2: 0,
            colorStops: [
              { offset: 0, color: 'rgba(129, 202, 254, 1)' },
              { offset: 1, color: 'rgba(59, 170, 250, 1)' },
            ],
          },
        },
        tooltip: {
          show: false,
        },
      },
      // 预测产量 - 柱体
      {
        z: 1,
        name: '预测产量',
        type: 'bar',
        data: millUnitTarget.value,
        yAxisIndex: 0,
        barWidth: 15,
        barGap: '50%',
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            x2: 1,
            y: 0,
            y2: 0,
            colorStops: [
              { offset: 0, color: 'rgba(20, 67, 133, 1)' },
              { offset: 0.5, color: 'rgba(59, 170, 250, 1)' },
              { offset: 0.5, color: 'rgba(16, 79, 149, 1)' },
              { offset: 1, color: 'rgba(23, 98, 182, 1)' },
            ],
          },
        },
        label: {
          show: false
        },
        animationDelay: function (idx: number) {
          return idx * 50;
        }
      },
      // 实际产量 - 钻石顶部
      {
        z: 2,
        name: '实际产量',
        type: 'pictorialBar',
        symbolPosition: 'end',
        data: millUnitActual.value,
        symbol: 'diamond',
        symbolOffset: ['70%', '-40%'],
        symbolSize: [15, 13],
        yAxisIndex: 0,
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            x2: 1,
            y: 0,
            y2: 0,
            colorStops: [
              { offset: 0, color: 'rgba(149, 251, 244, 1)' },
              { offset: 1, color: 'rgba(62, 207, 247, 1)' },
            ],
          },
        },
        tooltip: {
          show: false,
        },
      },
      // 实际产量 - 柱体
      {
        z: 1,
        name: '实际产量',
        type: 'bar',
        data: millUnitActual.value,
        yAxisIndex: 0,
        barWidth: 15,
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            x2: 1,
            y: 0,
            y2: 0,
            colorStops: [
              { offset: 0, color: 'rgba(28, 121, 153, 1)' },
              { offset: 0.5, color: 'rgba(69, 207, 216, 1)' },
              { offset: 0.5, color: 'rgba(37, 149, 180, 1)' },
              { offset: 1, color: 'rgba(18, 91, 111, 1)' },
            ],
          },
        },
        label: {
          show: false
        },
        animationDelay: function (idx: number) {
          return idx * 50 + 25;
        }
      },
      {
        name: '达成率',
        type: 'line',
        data: millUnitAchiRate.value,
        yAxisIndex: 1,
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        lineStyle: {
          color: '#91cc75',
          width: 2.5
        },
        itemStyle: {
          color: '#91cc75',
          borderColor: '#fff',
          borderWidth: 2
        },
        emphasis: {
          focus: 'series',
          itemStyle: {
            borderWidth: 3
          }
        },
        animationDelay: function (idx: number) {
          return idx * 30;
        }
      },
    ],
    animation: true,
    animationDuration: 1000,
    animationEasing: 'cubicOut'
  } as any;
  productionChartInstance.setOption(option, true);
};

// 窗口大小变化处理
const handleProductionChartResize = () => {
  nextTick(() => {
    productionChartInstance?.resize();
  });
};

// 监听数据变化，更新产量图表（按照 index old.vue 的方式）
watch(
  [millUnitX, millUnitTarget, millUnitActual, millUnitAchiRate],
  () => {
    updateProductionChart();
  },
  { deep: true }
);

// 获取日计划下达产量和达成率数据（新接口）
const fetchOutputPlanAct = async () => {
  try {
    // 通过 eapi 代理调用接口（POST请求）
    const result = await fetchDataWithRetry(() =>
      axios.post('/eapi/tcmReport/findOutputPlanAct', {}, { signal: controller.signal })
    );

    // 解析返回数据
    // 接口返回结构：{ data: { dayPlan, dayPlanXiada, dayPlanRate, dayAct, dayActRate }, ... }
    if (result?.data) {
      const data = result.data.data || result.data;

      if (data) {
        // 更新日计划数据
        dayPlan.value = Number(data.dayPlan || 0);
        dayPlanXiada.value = Number(data.dayPlanXiada || 0);
        dayPlanRate.value = Number(data.dayPlanRate || 0);
        dayAct.value = Number(data.dayAct || 0);
        dayActRate.value = Number(data.dayActRate || 0);
      }
    }
  } catch (error: any) {
    if (axios.isCancel(error)) {
      console.log('Request canceled: fetchOutputPlanAct');
      return;
    }
    console.error('❌ 获取日计划下达产量和达成率数据失败:', error);
  }
};

// 获取日产量、日产记录、月产量、月产记录、月设定产量、月完成率数据
const fetchTcmOutputRecord = async () => {
  try {
    const response = await acidRollingApi.tcmOutputRecord();

    if (response?.data?.data) {
      const data = response.data.data;
      console.log(
        '[fetchTcmOutputRecord] 接口返回:',
        JSON.stringify({
          outputWtDay: data.outputWtDay,
          outputWtDayRecord: data.outputWtDayRecord,
          outputWtMonth: data.outputWtMonth,
          outputWtMonthRecord: data.outputWtMonthRecord,
          outputWtMonthSet: data.outputWtMonthSet,
          overRate: data.overRate,
        })
      );

      // 更新日产量
      if (data.outputWtDay !== undefined && data.outputWtDay !== null) {
        dailyProduction.value = Number(data.outputWtDay) || 0;
      }

      // 更新日产记录（字段名：outputWtDayRecord）
      if (data.outputWtDayRecord !== undefined && data.outputWtDayRecord !== null) {
        dailyTopProd.value = Number(data.outputWtDayRecord) || 0;
      }

      // 更新月产量
      if (data.outputWtMonth !== undefined && data.outputWtMonth !== null) {
        monthProduction.value = Number(data.outputWtMonth) || 0;
      }

      // 更新月产记录（字段名：outputWtMonthRecord）
      if (data.outputWtMonthRecord !== undefined && data.outputWtMonthRecord !== null) {
        monthTopProd.value = Number(data.outputWtMonthRecord) || 0;
      }

      // 更新月设定产量
      if (data.outputWtMonthSet !== undefined && data.outputWtMonthSet !== null) {
        monthSet.value = Number(data.outputWtMonthSet) || 0;
      }

      // 更新月完成率（字段名：overRate，需要乘以100转换为百分比）
      if (data.overRate !== undefined && data.overRate !== null) {
        monthRate.value = Math.round(Number(data.overRate) * 100);
      }
    }
  } catch (error: any) {
    if (axios.isCancel(error)) {
      console.log('Request canceled: fetchTcmOutputRecord');
      return;
    }
    console.error('❌ 获取产量数据失败:', error);
  }
};

// 获取钢卷运行时间
// 接口说明：调用 /rest/restApi?name=TCM2280_TrLength 获取当前钢卷已运行长度（res.count）
// 用途：用于计算剩余时长 = 计划总时长(outputSe) - 已运行长度(count)
// 调用频率：每秒调用一次，首次获取运行长度，后续每秒递减
const getCoilRunTime = async () => {
  if (firstIn && rollCoilData.value) {
    try {
      // NewFulllineTrack.vue 使用: request.get(`/rest/restApi?name=${technologicalName}_TrLength`)
      // 返回 res.count，不是 res.data.count
      const res = await fetchDataWithRetry(() =>
        axios.get(`http://10.171.7.100:8090/restapi?name=${technologicalName}_TrLength`, { signal: controller.signal })
      );
      // 注意：axios 返回 res.data，但 NewFulllineTrack.vue 的 request 可能直接返回数据
      // 尝试两种方式：res.data.count 或 res.count
      const runTime = (res.data && res.data.count !== undefined) ? res.data.count : (res.count || 0);
      // 使用 outputSe 字段（兼容 OUTPUT_SE）
      const planTime = rollCoilData.value.outputSe || rollCoilData.value['OUTPUT_SE'] || 0;
      rollCoilLeftTime.value = planTime - runTime;
      firstIn = false;
    } catch (error: any) {
      if (axios.isCancel(error)) {
        console.log('Request canceled: getCoilRunTime');
        return;
      }
      console.error('获取钢卷运行时间失败:', error);
    }
  } else if (!firstIn) {
    rollCoilLeftTime.value--;
  }
};

// 获取钢卷数据
// 接口说明：调用 /eapi/acideff/getSingleRollSec 获取钢卷详细信息（GET请求，参数 entId）
// 用途：获取钢卷的计划总时长(outputSe)，用于计算剩余时长显示
// 触发时机：当检测到新的钢卷ID时（zones[29].entId 变化时）调用
const getRollCoilData = async (coilId: string) => {
  try {
    // 使用新的接口：/eapi/acideff/getSingleRollSec?entId=${coilId}（GET请求）
    const result = await fetchDataWithRetry(() =>
      axios.get(`/eapi/acideff/getSingleRollSec?entId=${coilId}`, { signal: controller.signal })
    );
    // axios 返回 result.data，尝试多种可能的响应结构
    // 如果 result.data.data 是数字，直接使用；如果是对象，尝试获取 outputSe 字段
    let planTime = null;
    if (result?.data) {
      // 如果 data 直接是数字
      if (typeof result.data === 'number') {
        planTime = result.data;
      }
      // 如果 data.data 是数字
      else if (result.data.data !== undefined && typeof result.data.data === 'number') {
        planTime = result.data.data;
      }
      // 如果 data 是对象，尝试获取 outputSe 字段
      else if (result.data.outputSe !== undefined) {
        planTime = result.data.outputSe;
      }
      // 如果 data.data 是对象，尝试获取 outputSe 字段
      else if (result.data.data && result.data.data.outputSe !== undefined) {
        planTime = result.data.data.outputSe;
      }
      // 兼容旧字段名 OUTPUT_SE
      else if (result.data.OUTPUT_SE !== undefined) {
        planTime = result.data.OUTPUT_SE;
      }
      else if (result.data.data && result.data.data.OUTPUT_SE !== undefined) {
        planTime = result.data.data.OUTPUT_SE;
      }
    }

    if (planTime !== null && planTime !== undefined) {
      rollCoilData.value = { outputSe: planTime };
      rollCoilAllTime.value = planTime;
      rollCoilLeftTime.value = rollCoilAllTime.value;
      firstIn = true; // 重置标志，让 getCoilRunTime 重新获取运行长度
    }
  } catch (error: any) {
    if (axios.isCancel(error)) {
      console.log('Request canceled: getRollCoilData');
      return;
    }
    console.error('获取钢卷数据失败:', error);
  }
};

// 获取PDI数据用于小时吨钢
const getPidMesInfo = async () => {
  try {
    const result = await rollingSimulationApi.getSteelInfo(coilIds.value, { signal: controller.signal });
    if (result?.data?.data && Array.isArray(result.data.data)) {
      const realCoilId = coilIds.value[0];
      for (let index = 0; index < result.data.data.length; index++) {
        const element = result.data.data[index];
        if (element.entid == realCoilId) {
          TVData.value = {
            value: element.OUTPUT_PH || 0,
            title: '小时吨钢',
          };
          break;
        }
      }
    }
  } catch (error: any) {
    console.error('获取PDI数据失败:', error);
  }
};

// 获取钢卷数据（包含目标厚度）- 修改为新接口
// 获取钢卷目标厚度数据
const getCoilData = async (zones: any) => {
  if (!zones?.[28]?.entId) return;

  try {
    const result = await axios.post('/eapi/tPdiData_tcm2280/findByEntID', {
      condition: { entid: zones[28].entId }
    });

    if (result?.data?.data?.controlthick) {
      Targetthickness.value = Number(result.data.data.controlthick) || 0;
    }
  } catch (error) {
    console.error('获取钢卷数据失败:', error);
  }
};

// 监听酸位数据变化，初始化图表（删除，改为在fetchGaugeData中初始化）
// watch(acidLevels, (newVal) => {
//   if (newVal && newVal.length > 0) {
//     nextTick(() => {
//       if (acidBarsChartInstance === null) {
//         initAcidBarsChart();
//       }
//     });
//   }
// }, { immediate: true });

// 状态信息卡片点击处理函数
const handleStatusCardClick = (type: string) => {
  const routeMap: Record<string, string> = {
    '异常设备状态': '/acidRollingProductionEfficiency/analysisdiagnosis',
    '停机信息录入': '/acidRollingProductionEfficiency/shutdownStatistics',
    '换辊统计': '/acidRollingProductionEfficiency/rollchange',
    '重焊统计': '/acidRollingProductionEfficiency/reWeldingFrequencyTraceability',
    '异常剪切状态': '/acidRollingProductionEfficiency/productionschedulereport',
    '开卷机异常统计': '/acidRollingProductionEfficiency/analysisdiagnosis', // 暂时使用分析诊断页面
  };

  const path = routeMap[type];
  if (path) {
    router.push({ path });
  }
};

</script>
<style scoped lang="less">
.home1 {
  width: 100vw;
  background-color: rgba(2, 6, 53, 1);
  position: relative;
}

.header {
  position: relative;
  z-index: 10000; // 设置非常高的 z-index，确保显示在最上层
}

.titleMain {
  position: relative;
  z-index: 10001; // 设置非常高的 z-index，确保显示在最上层

  h1 {
    position: relative;
    z-index: 10002; // 设置非常高的 z-index，确保显示在最上层
  }
}

.page-layout {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  gap: 1vh;
  margin-top: -6vh; // 从 -5vh 改为 -8vh，让内容上移更多
  padding: 10px 20px; // 减少顶部内边距，从 20px 改为 10px 20px
  width: 99.5%;
}

.area {
  background-color: rgba(12, 37, 87, 0.5);
  // border: 1px solid rgba(19, 163, 255, 0.25);
  border: 1px solid;
  border-image: linear-gradient(180deg,
      rgba(19.0000007674098, 163.00000548362732, 255, 0.250980406999588),
      rgba(19.0000007674098, 163.00000548362732, 255, 0.250980406999588),
      rgba(19.0000007674098, 163.00000548362732, 255, 0.4000000059604645)) 1 1;
  padding: 12px;
}

.tag {
  border: 1px solid rgba(62, 126, 218, 0.5);
  border-left: 3px solid rgba(27, 100, 245, 1);
  // border-right: 1px solid;
  // border-bottom: 1px solid;
  display: flex;
  flex-direction: column;
  gap: 1vh;
  position: absolute;
  background-color: rgba(6, 54, 138, 0.4);
  padding: 8px 4px;
  font-weight: 400;
  font-size: 12px;
  z-index: 3;
  // border-image: linear-gradient(
  //     270deg,
  //     rgba(62.00000010430813, 126.00000008940697, 218.00000220537186, 0.5),
  //     rgba(62.00000010430813, 126.00000008940697, 218.00000220537186, 0),
  //     rgba(0, 0, 0, 0)
  //   )
  //   1 1;

  span {
    color: #fff;
    font-size: 14px;
    font-weight: 400;
  }

  .flag {
    display: flex;
    flex-wrap: nowrap;
    gap: 1vw;
    align-items: baseline;

    .el-text {
      color: #f55b5b;
      font-weight: 400;
      font-size: 12px;
    }
  }
}

.top-svg {
  height: 30vh;
  width: 100%;
  position: relative;
  margin-top: -4vh; // 添加负边距，让SVG区域上移

  .value-text {
    font-size: 16px;
    font-family: 'Source Han Sans-Regular', sans-serif;
  }

  .icon {
    height: 2vh;
    width: 3vw;
    border-radius: 4px;
    display: flex;
    align-items: center;
    text-align: center;
    justify-content: center;
    font-size: 12px;
  }

  .open {
    border: 1px solid rgba(245, 91, 91, 1);
    color: rgba(245, 91, 91, 1);
    background-color: rgba(245, 91, 91, 0.15);
  }

  .relax {
    border: 1px solid rgba(99, 231, 117, 1);
    color: rgba(99, 231, 117, 1);
    background-color: rgba(99, 231, 117, 0.15);
  }

  .closed {
    border: 1px solid rgba(204, 204, 204, 1);
    color: rgba(204, 204, 204, 1);
    background-color: rgba(204, 204, 204, 0.15);
  }

  .tr-length {
    position: absolute;
    z-index: 3;

    span {
      font-weight: 400;
      font-size: 18px;
      color: #fff;
      font-family: 'Source Han Sans-Regular', sans-serif;
    }
  }

  // 速度仪表盘
  .speed-gauge {
    position: absolute;
    z-index: 889;
    width: 35%;
    height: 35%;
  }

  #middle_speed1 {
    left: -14vw;
    top: 2vh;
  }

  #middle_speed2 {
    left: 59vw;
    top: 3vh;
  }

  #middle_speed4 {
    left: 38vw;
    top: 15vh;
    z-index: 892;
  }

  #middle_speed5 {
    left: 31.5vw;
    top: 15vh;
    z-index: 892;
  }

  // 轧机入口速度（白色字体显示，无背景）
  .speed-text {
    position: absolute;
    z-index: 892;
    color: #fff;
    font-weight: bold;
    font-size: 0.8vw;
    text-align: center;

    p {
      margin: 0;
      line-height: 1.2;
    }
  }

  #middle_speed6 {
    left: 24vw;
    top: 12vh;
  }

  // 半透明框样式
  .semitransp_box {
    border-radius: 4px;
    background: #063E90;
    width: fit-content;
    text-align: center;
    align-content: center;
    color: #fff;
    height: 1.4vw;
    position: absolute;
    z-index: 10; // 确保所有蓝条在SVG之上（SVG的z-index是2）

    p,
    p span {
      display: inline;
      font-size: 0.65vw;
    }

    p:last-child,
    p:last-child span {
      color: #fff;
      font-weight: 600;
    }
  }

  // 延伸率
  .elongation_set {
    background: unset;
    left: 60vw;
    top: 8vh;
    padding: 0 1rem;
  }

  .elongation_act {
    background: unset;
    left: 64vw;
    top: 8vh;
    padding: 0 1rem;
  }

  // 拉矫机模式
  .sub_open {
    left: 69.8vw;
    width: 2.5vw;
    top: 6vh;
  }

  .sub_relax {
    left: 69.8vw;
    width: 2.5vw;
    top: 9vh;
  }

  .sub_closed {
    left: 69.8vw;
    width: 2.5vw;
    top: 12vh;
  }

  // 活套信息
  .inlet_looper {
    left: 67vw;
    width: 6vw;
    top: 27.3vh;
  }

  .inlet_looper_time {
    left: 59.3vw;
    width: 7.5vw;
    top: 27.3vh;
  }

  .export_looper {
    left: 32vw;
    width: 6vw;
    top: 27.3vh;
  }

  .export_looper_time {
    left: 38.3vw;
    top: 27.3vh;
    width: 7.5vw;
  }

  // 速度信息
  .ypj_speed {
    left: 46.5vw;
    width: 6vw;
    top: 27.3vh;
  }

  .tcm_speed {
    left: 53vw;
    width: 6vw;
    top: 27.3vh;
  }

  // 开卷机剩余长度
  .uncoiler_remaining_length_a {
    left: 94vw;
    text-align: left;
    width: 10vw;
    padding-left: 0.5vw;
    top: 12vh;
    background: transparent !important;
    border: none !important;
  }

  .uncoiler_remaining_length_b {
    text-align: left;
    width: 10vw;
    padding-left: 0.5vw;
    left: 92.8vw;
    top: 19.8vh;
    background: transparent !important;
    border: none !important;
  }

  // 卷取长度
  .coiler_remaining_length_a {
    text-align: left;
    width: 7.6vw;
    padding-left: 0.5vw;
    left: 0vw;
    top: 23vh;
  }

  // 厚度偏差
  .targetthickness {
    text-align: left;
    width: 7.6vw;
    padding-left: 0.5vw;
    left: 0vw;
    top: 20vh;
  }

  // 轧机入口速度
  .mill_enter_speed {
    left: 19vw;
    top: 12vh;
    width: 8vw;
  }

  // 工艺段套量
  .tech_loop {
    left: 40vw;
    top: 7vh;
    padding: 0 0.5rem;
  }

  // 新增：5个小蓝条样式（位置待调整）
  //出口段AI设定值
  .blue_bar_1 {
    left: 0.66vw;
    top: 9vh;
    padding: 0 0.5rem;
  }

  .blue_bar_2 {
    left: 52.5vw;
    top: 22vh;
    padding: 0 0.5rem;
  }

  .blue_bar_3 {
    right: 18.6vw;
    top: 10vh;
    padding: 0 0.5rem;
  }

  .blue_bar_4 {
    right: 12.5vw;
    top: 6vh;
    padding: 0 0.5rem;
    background: transparent !important;
    border: none !important;

    p {
      color: #fff !important;
    }
  }

  .blue_bar_5 {
    right: 12.5vw;
    top: 16vh;
    padding: 0 0.5rem;
    background: transparent !important;
    border: none !important;

    p {
      color: #fff !important;
    }
  }

  // 1#矫直机压下量

  .blue_bar_6 {
    right: 2.5vw;
    top: 2.5vh;
    padding: 0 0.5rem;
    background: transparent !important;
    border: none !important;

    p {
      color: #fff !important;
      font-size: 9px;
    }
  }

  .blue_bar_7 {
    right: 2.5vw;
    top: 7.8vh;
    padding: 0 0.5rem;
    background: transparent !important;
    border: none !important;

    p {
      color: #fff !important;
      font-size: 9px;
    }
  }

  .blue_bar_8 {
    right: 6.5vw;
    top: 2.5vh;
    padding: 0 0.5rem;
    background: transparent !important;
    border: none !important;

    p {
      color: #fff !important;
      font-size: 9px;
    }
  }

  .blue_bar_9 {
    right: 5.7vw;
    top: 7.8vh;
    padding: 0 0.5rem;
    background: transparent !important;
    border: none !important;

    p {
      color: #fff !important;
      font-size: 9px;
    }
  }

  // 2#矫直机压下量
  .blue_bar_10 {
    right: 5.5vw;
    top: 12.6vh;
    padding: 0 0.5rem;
    background: transparent !important;
    border: none !important;

    p {
      color: #fff !important;
      font-size: 9px;
    }
  }

  .blue_bar_11 {
    right: 5.5vw;
    top: 18.3vh;
    padding: 0 0.5rem;
    background: transparent !important;
    border: none !important;

    p {
      color: #fff !important;
      font-size: 9px;
    }
  }

  .blue_bar_12 {
    right: 8.5vw;
    top: 12.6vh;
    padding: 0 0.5rem;
    background: transparent !important;
    border: none !important;

    p {
      color: #fff !important;
      font-size: 9px;
    }
  }

  .blue_bar_13 {
    right: 8.8vw;
    top: 18.3vh;
    padding: 0 0.5rem;
    background: transparent !important;
    border: none !important;

    p {
      color: #fff !important;
      font-size: 9px;
    }
  }

  // 拉矫机模式
  .blue_bar_14 {
    left: 69.7vw;
    top: 2.5vh;
    padding: 0 0.5rem;
  }

  // 烘干箱温度
  .blue_bar_16 {
    left: 46vw;
    top: 8.5vh;
    padding: 0 0.5rem;
    background: transparent !important;
    border: none !important;

    p {
      color: #fff !important;
    }
  }

  // 酸位柱状图ECharts容器
  .acid-bars-svg {
    position: absolute;
    right: 31vw;
    top: 15vh;
    z-index: 999 !important; // 提高z-index，确保显示在最上层
    width: 6vw;
    height: 10vh;
    pointer-events: auto !important; // 确保可以接收鼠标事件
  }

  // 产量信息卡片
  .dailyProduction_info {
    position: absolute;
    left: 33vw;
    top: -16vh;
    z-index: 10;
    height: 24%;
  }

  .monthProduction_info {
    position: absolute;
    height: 24%;
    z-index: 10;
    left: 33vw;
    top: -7vh;
  }

  .dailyProdTop_info {
    position: absolute;
    height: 24%;
    z-index: 10;
    left: 40vw;
    top: -16vh;
  }

  .monthProdTop_info {
    position: absolute;
    height: 24%;
    z-index: 10;
    left: 40vw;
    top: -7vh;
  }

  .monthProdSet {
    position: absolute;
    height: 24%;
    z-index: 10;
    left: 33vw;
    top: 2vh;
  }

  .monthProdRate {
    position: absolute;
    height: 24%;
    z-index: 10;
    left: 40vw;
    top: 2vh;
  }

  // 小时吨钢
  .TV_info {
    position: absolute;
    left: -9.5vw;
    top: -16vh;
    z-index: 900;
    width: 26%;
    height: 24%;
  }

  .TV_ACT_info {
    position: absolute;
    left: -9.5vw;
    top: -7vh;
    z-index: 900;
    width: 26%;
    height: 24%;
  }

  // 剩余时长进度条
  .time_div {
    height: 2vh;
    position: absolute;
    bottom: 4.2vh;
    border-radius: 2vh;
    left: 2vw;
  }

  .all_time {
    background: #063E90;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;

    span {
      z-index: 999;
    }
  }

  .normal_time {
    top: 0;
    background: #00c600;
    left: 13vw;
  }

  .out_time {
    top: 0;
    background: #c60000;
    right: 13vw;
  }

  // 红色文本
  .text-red {
    color: #FE2E2E !important;
  }
}

.container {
  display: flex;
  flex-wrap: nowrap;
  gap: 1vw;
  width: 100%;

  .main-container {
    display: flex;
    flex-direction: column;
    gap: 1vh;
    flex: 1;
  }
}

.coils {
  display: flex;
  flex-direction: column;
  gap: 1.1vh;
}

// .coils-info {
//   // display: grid;
//   // grid-template-columns: repeat(3, 1fr);
//   display: flex;
//   flex-wrap: nowrap;
//   gap: 0.5vw;
//   .item {
//     display: flex;
//     flex-direction: column;
//     gap: 0.5vh;
//     font-size: 12px;
//   }

//   .text {
//     background-image: linear-gradient(to bottom, rgba(255, 255, 255, 1), rgba(127, 198, 243, 1));
//     -webkit-background-clip: text;
//     background-clip: text;
//     -webkit-text-fill-color: transparent;
//   }

//   .gradient-bars {
//     height: 1vh;
//     width: 100%;
//     background-size: 5px 100%;
//     background-repeat: repeat-x;
//   }
// }

.coils-info {
  display: flex;
  flex-direction: column;
  gap: 0.2vh;
  width: 100%;

  .coils-info-item {
    width: 100%;
    display: grid;
    gap: 1vw;
    grid-template-columns: repeat(3, 1fr);
    text-align: end;

    .coils-info-item-content {
      display: flex;
      flex-wrap: nowrap;
      align-items: flex-start;
      gap: 1rem;

      // .coils-info-data {
      //   display: flex;
      //   flex-direction: row;
      //   flex-wrap: nowrap;
      //   gap: 0.5vw;
      //   align-items: center;
      //   width: 100%;
      //   // 数据靠左显示
      //   justify-content: flex-start;

      .text-coil {
        font-weight: 400;
        font-size: 16px;
        font-family: 'YouSheBiaoTiHei', sans-serif;
        // 使用color而不是background-clip，因为需要显示颜色
      }

      .text-data {
        font-weight: 700;
        font-size: 14px;
        font-family: 'DINCondensed-bold', sans-serif;
        background-image: linear-gradient(to bottom, rgba(255, 255, 255, 1), rgba(127, 198, 243, 1));
        -webkit-background-clip: text;
        background-clip: text;
        -webkit-text-fill-color: transparent;
        color: #ffffff; // 备用颜色
      }
    }

    // }

    .coils-info-bars {
      height: 1.5vh;
      display: flex;
      flex-wrap: nowrap;
      // position: absolute; // 绝对定位，相对于 .coils-info-item
      // bottom: 0; // 底部对齐
      z-index: 1;
      min-width: 0;
    }
  }
}

.areas {
  display: grid;
  grid-template-columns: repeat(8, 1fr);
}

.areas2 {
  display: flex;
  flex-wrap: nowrap;
  height: 30vh;
}

.areas,
.areas2 {
  gap: 0.5vw;

  .area {
    padding: 5px 2px;
  }

  .title {
    display: flex;
    flex-wrap: nowrap;
    align-items: center;

    img {
      margin-top: -0.2vh;
    }

    span {
      color: #ffffff;
      font-weight: 700;
      font-size: 16px;
      font-family: '江城斜黑体', sans-serif;
      background-image: linear-gradient(to bottom, rgba(49, 190, 255, 1), rgba(255, 255, 255, 1));
      -webkit-background-clip: text;
      background-clip: text;
      -webkit-text-fill-color: transparent;
    }
  }
}

.acid-level {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  padding: 2px 5px;
  gap: 0.5vw;

  .acid-level-item {
    margin-top: 2vh;
    display: flex;
    flex-direction: column;
    gap: 1vh;

    .acid-level-item-text {
      font-weight: 400;
      font-size: 14px;
      color: #ffffff;
      line-height: 20px;
      text-align: center;
    }

    .acid-level-item-bar {
      height: 15vh;
      background-color: #091f4f;
      display: flex;
      justify-content: center;
      align-items: flex-end; // 从底部对齐
      padding-bottom: 0; // 确保柱子贴底

      .acid-level-item-bar-inner {
        width: 40%;
        // 高度通过内联样式动态设置: height: `${getBarHeight(value)}%`
        // 渐变色从顶部（最高）到底部（最低）
        background-image: linear-gradient(to bottom, #e57c19, #f4e079);
        transition: height 0.3s ease; // 添加过渡效果
      }
    }
  }
}

.areas2-garph1 {
  width: 40%;
  height: 100%; // 让卡片高度适应内容
  display: flex;
  flex-direction: column;
  
  // 柱状图容器（占80%，让柱状图更突出）
  .realtime-chart-container {
    height: 60%;
    min-height: 18vh;
    margin-top: -2vh;
    flex-shrink: 0;
  }
  
  // 表格容器（占20%，紧凑显示）
  .realtime-table-container {
    height: 30%;
    min-height: 5vh;
    margin-top: 0.3vh;
    overflow: hidden;
    flex-shrink: 0;
  }
  
  // 表格样式（参考 continuousrefund/index.vue）
  :deep(.el-table) {
    background-color: transparent !important;
    --el-table-row-hover-bg-color: rgba(0, 246, 255, 0.1);
    font-size: 11px;
    
    .el-table__header-wrapper {
      .el-table__header {
        th {
          background-color: #2f59af !important;
          color: #fff !important;
          border: none !important;
          padding: 3px 0 !important;
          font-weight: 600;
          font-size: 11px;
        }
      }
    }
    
    .el-table__body-wrapper {
      max-height: 100%;
      overflow-y: auto;
      
      &::-webkit-scrollbar {
        width: 3px;
        height: 3px;
      }
      
      &::-webkit-scrollbar-track {
        background: rgba(0, 24, 48, 0.3);
      }
      
      &::-webkit-scrollbar-thumb {
        background: rgba(0, 246, 255, 0.5);
        border-radius: 2px;
        
        &:hover {
          background: rgba(0, 246, 255, 0.7);
        }
      }
      
      .el-table__body {
        tr {
          background-color: rgba(22, 37, 86, 0.6) !important;
          
          &:nth-child(odd) {
            background-color: rgba(34, 54, 113, 0.6) !important;
          }
          
          &:hover {
            background-color: rgba(0, 246, 255, 0.15) !important;
          }
          
          td {
            background-color: transparent !important;
            border: none !important;
            padding: 1px 0 !important;
            color: rgba(255, 255, 255, 0.7) !important;
            font-size: 10px;
            
            .cell {
              background-color: transparent !important;
              border: none !important;
              line-height: 14px !important;
              padding: 0 4px !important;
            }
          }
        }
      }
    }
    
    .el-table__inner-wrapper::before {
      background-color: rgba(23, 61, 145, 0.5) !important;
    }
  }
}

.swtichDate {
  position: relative;

  .el-radio-group {
    position: absolute;
    right: 1vw;
    top: -3.6vh;
  }
}

.status-info {
  display: flex;
  flex-wrap: nowrap;
  gap: 0.3vw;

  .info-item {
    position: relative;
    cursor: pointer;
    transition: all 0.3s ease;
    // align-items: center;

    &:hover {
      transform: translateY(-5px);
      filter: brightness(1.2);

      .item-bg {
        filter: brightness(1.15);
      }

      .item-icon {
        filter: brightness(1.2);
      }

      .item-text span {
        text-shadow: 0 0 10px rgba(49, 190, 255, 0.8);
      }
    }

    &:active {
      transform: translateY(-2px);
      filter: brightness(0.95);
    }
  }

  .item-bg {
    position: absolute;
    z-index: 2;
    bottom: 1.7vh;
  }

  .item-icon {
    position: absolute;
    bottom: 2.5vh;
    left: 0.6vw;
    z-index: 3;
  }

  .item-text {
    position: absolute;
    bottom: 2.7vh;
    left: 2.8vw;
    z-index: 3;

    span {
      font-size: 16px;
      font-weight: 700;
      font-family: '江城斜黑体', sans-serif;
      background-image: linear-gradient(to bottom, rgba(49, 190, 255, 1), rgba(255, 255, 255, 1));
      -webkit-background-clip: text;
      background-clip: text;
      -webkit-text-fill-color: transparent;
    }
  }
}

.prod-info {
  display: flex;
  flex-wrap: nowrap;
  gap: 0.7vw;

  .prod-item {
    display: flex;
    flex-direction: column;
    gap: 0.5vh;
    align-items: center;
    justify-content: center;
  }

  .data {
    font-size: 16px;
    font-weight: 700;
    background-image: linear-gradient(to bottom, rgba(255, 255, 255, 1), rgba(127, 198, 243, 1));
    -webkit-background-clip: text;
    background-clip: text;
    -webkit-text-fill-color: transparent;
  }

  .data-text {
    font-size: 14px;
    color: rgba(105, 192, 239, 1);
    font-weight: 400;
  }
}

.prod-item {
  display: flex;
  flex-direction: column;
  gap: 0.5vh;
  align-items: center;
  justify-content: center;
}

.data {
  font-size: 16px;
  font-weight: 700;
  background-image: linear-gradient(to bottom, rgba(255, 255, 255, 1), rgba(127, 198, 243, 1));
  -webkit-background-clip: text;
  background-clip: text;
  -webkit-text-fill-color: transparent;
}

.data-text {
  font-size: 14px;
  color: rgba(105, 192, 239, 1);
  font-weight: 400;
}

.plan-prod {
  display: flex;
  flex: 1;
  flex-direction: row;
  gap: 18px;
  align-items: center;
  justify-content: center;
}

:deep(.el-radio-button__inner) {
  color: rgba(216, 240, 255, 0.5);
  text-shadow: 0px 0px 4px #0091ff;
  font-weight: 400;
  font-size: 12px;
  background-color: transparent;
  border: 1px solid rgba(30, 123, 214, 0.3);
}

:deep(.el-radio-button.is-active .el-radio-button__original-radio:not(:disabled) + .el-radio-button__inner) {
  color: #d8f0ff;
  text-shadow:
    0px 0px 10px #0091ff,
    0px 0px 4px #0091ff;
  font-weight: 400;
  font-size: 12px;
  background-color: transparent;
  border: 1px solid rgba(30, 123, 214, 0.8);
}

:deep(.el-radio-button:first-child .el-radio-button__inner) {
  border-left: 1px solid rgba(30, 123, 214, 0.3);
}

.pie-info {
  .sub-t {
    font-weight: 400;
    font-size: 14px;
    color: #fff;
    text-align: left;
    align-items: center;
  }

  .main-t {
    font-size: 26px;
    font-weight: 700;
    font-family: 'DINCondensed-bold', sans-serif;
    color: rgba(34, 217, 248, 1);
    text-align: center;
    align-items: center;
  }
}

// 活套套量柱状图样式（按照 index old.vue 的方式）
.arpe-chart {
  width: 100%;
  height: 100%;
}

.arpe-chart-legend {
  font-size: 13px;
  text-align: left;
  margin-top: 2px;
  letter-spacing: 2px;
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

// 辊位图弹窗样式 - 降低 z-index
:deep(.roll-details-dialog) {
  z-index: 999 !important; // 降低弹窗层级到999，确保低于header(10000)
}

:deep(.roll-details-mask) {
  z-index: 998 !important; // 遮罩层设置为998，低于弹窗
}

// 确保弹窗容器也有正确的层级
:deep(.el-overlay) {
  z-index: 998 !important; // overlay层级也要低于header
}
</style>
